I am working on a socket based chat room that integrates into my site but I am having a little difficulty trying to understand a few things when it comes to socket servers.
The first thing I am trying to figure out is how to separate users into multiple rooms. How this should work is… A user connects to the server via the flash chat. Database information is included in the flash params such as Username, text color, and room to enter. The flash then sends this information to the socket server. So far, everything to this point is good to go. What I am having problems with is how to have the script on the server separate the users and remember who is who without using a database connection.
Here is what I have so far :
#!/usr/bin/php -q
<?php
error_reporting(E_ALL);
//set_time_limit(0);
ob_implicit_flush();
$address = '0.0.0.0';
$port = 5545;
//---- Function to Send out Messages to Everyone Connected ----------------------------------------
function send_Message($allclient, $socket, $buf) {
foreach($allclient as $client) {
socket_write($client, "$socket wrote: $buf");
}
}
function XML2array($xml){
$xml = simplexml_load_string($xml);
$xarray = array();
$xmlname = $xml->getName();
foreach($xml->Attributes() as $key=>$att){
$xarray[$xmlname][$key] = $att;
}
$xmlchildren = $xml->children();
return $xarray;
}
//---- Start Socket creation for PHP 5 Socket Server -------------------------------------
if (($master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
echo "socket_create() failed, reason: " . socket_strerror($master) . "
";
}
socket_set_option($master, SOL_SOCKET,SO_REUSEADDR, 1);
if (($ret = socket_bind($master, $address, $port)) < 0) {
echo "socket_bind() failed, reason: " . socket_strerror($ret) . "
";
}
if (($ret = socket_listen($master, 5)) < 0) {
echo "socket_listen() failed, reason: " . socket_strerror($ret) . "
";
}
echo "Connected!
";
$read_sockets = array($master);
while (true) {
$changed_sockets = $read_sockets;
$num_changed_sockets = socket_select($changed_sockets, $write = NULL, $except = NULL, NULL);
foreach($changed_sockets as $socket) {
if ($socket == $master) {
if (($client = socket_accept($master)) < 0) {
echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "
";
continue;
} else {
array_push($read_sockets, $client);
echo "Client : ".$client." Connected!
";
}
} else {
$bytes = socket_recv($socket, $buffer, 2048, 0);
if ($bytes == 0) {
$index = array_search($socket, $read_sockets);
unset($read_sockets[$index]);
socket_close($socket);
echo "Client : ".$client." Left!
";
} else {
$allclients = $read_sockets;
$xml = XML2array($buffer);
if(!empty($xml[root][username])){
// Somehow save the users info for later use.....
}
array_shift($allclients);
echo "Client : ".$client." ".$buffer."
";
send_Message($allclients, $socket, $buffer);
}
}
}
}
?>