Page 1 of 1
PHP Socket Server (Chat)
Posted: Sat Jul 31, 2004 10:39 pm
by crazygamer
I'm trying to make a socket server so that I can telnet to it and chat with a friend. I've tried everything, but I can't get it to accept both connections. I've had it send welcome messages to both, but when I add the code for it to listen and forward anything it recieves, it stops after the first connection, and only forwards to the first one.
Does anyone know a way to make this kind of socket server which will support more than one user (nothing complicated, I just need to be able to read a message from either of the people, and then forward it to everyone connected).
TIA
Posted: Sat Jul 31, 2004 11:01 pm
by John Cartwright
show us what code you got so far
Posted: Sun Aug 01, 2004 11:10 am
by crazygamer
I was tinkering with the code so I think I changed it a little from what I had before. I think I had another do-while loop somewhere in there, but it seemed that there was no need for it. Does anyone know how to make it be able to listen for incoming messages, and also not get stuck on looking for new connections being made?
Code: Select all
<?php
// don't timeout
set_time_limit (0);
// set some variables
$host = "www.norcalmusic.net";
$port = 2222;
$connections = array();
$welcome = "\r\nConnected to chat server...\r\n";
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\r\n");
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\r\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\r\n");
do {
$nextAvailSlot = count($connections);
$connections[$nextAvailSlot] = socket_accept($socket);
socket_set_nonblock($connections[$nextAvailSlot]) or die("Could not set up nonblocking socket\r\n");
socket_write($connections[$nextAvailSlot], $welcome, strlen ($welcome)) or die("Could not send connect string\r\n");
if(count($connections) > 0) {
for($i = 0; $i < count($connections); $i++) {
$input = socket_read($connections[$i], 1024, 1) or die("Could not read input\r\n");
if (trim($input) != "") {
if (trim($input) == "__shutdown") {
for($j = 0; $j < count($connections); $j++) {
socket_write($connections[$j], "Closing all connections...\r\nShutting server down...\r\n", 51) or die("Could not write output\r\n");
socket_close($connections[$j]);
}
break 3;
} else if(trim($input) == "__quit") {
socket_write($connections[$i], "Closing your connection...\r\n", 27) or die("Could not write output\r\n");
socket_close($connections[$i]);
} else {
//send back
$output = $input . "\r\n";
for($k = 0; $k < count($connections); $k++) {
socket_write($connections[$k], $output, strlen($output)) or die("Could not write output\r\n");
}
}
}
}
}
} while (true);
// close primary socket
socket_close($socket);
?>
Posted: Mon Aug 02, 2004 11:34 am
by crazygamer
bump...
