View Single Post
03-26-2012, 01:19 AM
#3
newkid is offline newkid
Status: Junior Member
Join date: Sep 2006
Location:
Expertise: PHP,MySQL, HTML(5), CSS
Software: Photoshop, Sublime Text2,MS VS
 
Posts: 63
iTrader: 1 / 100%
 

newkid is on a distinguished road

Send a message via Skype™ to newkid

  Old

I already know how to create a chat with php just not using sockets. I have a particular reason for doing so...anyways. I created a socket server but have trouble allow several connections here is the code :

PHP Code:
<?php

// show errors
error_reporting(E_ALL);

// prevent timeout
set_time_limit(0);

// host IP and port
$hostIP "127.0.0.1";
$hostPort 1234;

echo 
"Connecting to "$hostIP ." ...\n";

// create socket and socket handle
$tchekemsock socket_create(AF_INETSOCK_STREAM0) or die("error: could not create socket\n");

// bind socket to IP and port and binded socket handle
$result socket_bind($tchekemsock$hostIP$hostPort) or die("err: could not bind socket to IP and port\n");

if (
$result){
    echo 
"Socket binded...\n";
    }

/* 
    determine max number of connections
    and start listening 
*/
$result socket_listen($tchekemsock5) or die("error: socket listening failed!\n");

if (
$result){
    echo 
"Listening...\n";
}

/*
    accept incoming client connections
    spawn another socket for communication
*/
$spawn socket_accept($tchekemsock) or die("error: could not accept incoming connection\n");

if (
$spawn){
    echo 
"Client connected!\n";
}

function 
sendmsg($socket$msg){

        if (
$socket){
            
socket_write($socket$msgstrlen($msg));
        }
}

sendmsg($spawn"Connection to Tchekem successfull!\n");


do {

     
/*
        read client input
        and determine max client input to read in bytes
    */
    
    
$input socket_read($spawn1024) or die("error: could not read input\n"); 

    if (
trim($input) != ""){
        
                
        
// input 
        
echo "input: ".  $input ."\n";
        
        
// if client enters end close socket
        
if (trim($input) == "end"){
        
            
sendmsg($spawn"socket clossing...");
            
socket_close($spawn);
            break;
//        }else{
                
            // reverse and send back input to client
            
$output "\nresponse >" strrev($input) ."\n";
            
socket_write($spawn$outputstrlen($output)) or die("error: Could not write to output to client");
            echo 
"sent out: "trim($input) ."\n";            
        }
        
    }
    
} while (
true);


// terminate both sockets
socket_close($spawn);
socket_close($tchekemsock);

echo 
"Socket disconnected";
I'm just testing the waters a bit with this, it is not the actual code I'll be using. Just want to make sure I understand it.