php网络编程。 执行php后,可以多个用户同时连上服务器进行聊天。
客户端可以用 telnet 程序。 只是个演示。 需要复杂功能自己完善。
if(!extension_loaded('sockets')) {
if(strtoupper(substr(PHP_OS, 0, 3)) == "WIN") {
dl('php_sockets.dll');
}
else {
dl('sockets.so');
}
}
// set_time_limit(0);
$address = '127.0.0.1';
$port = '123123';
$welcome_msg = "\\r\\nWelcome to the PHP Test Server.";
$welcome_msg .= "\\r\\nTo quit, type 'quit'. To shut down the server type 'shutdown'.\\r\\n";
$msg_len = 1024;
$msg_eof = "\\n"; //信息结束标记。
$usleep = 1000*100; //间隔周期。
$connections = array();
$commonProtocol = getprotobyname("tcp");
if(($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\\r\\n";
exit;
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\\r\\n";
exit;
}
if (socket_listen($sock, 15) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\\r\\n";
exit;
}
socket_set_nonblock($sock) or die('not set nonblock');
// Accept any incoming connections to the server
do {
@ $connection = socket_accept($sock);
if($connection) {
$connections[] = array('con'=>$connection, 'bufs'=>'');
socket_write($connection, $welcome_msg, strlen($welcome_msg));
unset($connection);
}
$talk_bufs = '';
foreach($connections as $xid => & $client) {
unset($bufs);
$connection = $client['con'];
$bufs = &$client['bufs'];
if(false === socket_write($connection, $talkback, strlen($talkback))) {
echo "socket_write() failed: reason: " . socket_strerror(socket_last_error($connection)) . "\\r\\n";
socket_close($connection);
unset($connections[$xid]);
continue;
}
// if (false === ($buf = socket_read($connection, $msg_len, PHP_NORMAL_READ))) {
if (false === ($buf = socket_read($connection, $msg_len))) {
continue;
}
$bufs .= $buf;
if(false === strpos($bufs, $msg_eof)) {
continue;
}
$buf = substr($bufs,0,(strrpos($bufs, $msg_eof)));
$bufs = substr(strrchr($bufs, $msg_eof), 1);
if (!$buf = trim($buf)) {
continue;
}
// 判断刷屏.有点苛刻。
if(strrpos($buf, $msg_eof) || (strlen($buf) > $msg_len)) {
$buf = 'quit';
}
if ($buf == 'quit' || $buf == 'exit') {
socket_close($connection);
unset($connections[$xid]);
continue;
}
if ($buf == 'shutdown') {
socket_close($connection);
break 2;
}
$talk_bufs .= "PHP: $xid said '$buf'.\\r\\n";
}
$talkback = $talk_bufs;
usleep($usleep);
} while(true);
socket_close($sock);
// 使用方法 telnet 连接 127.0.0.1 123123 端口,可以帮定外部ip。
// 使用的时候最好在 cli 方式下执行。