php写多服务,用php语言写一个聊天用的服务程序

这篇博客展示了如何使用PHP进行网络编程,创建一个简单的TCP聊天服务器。通过socket扩展,实现多用户同时连接并使用telnet客户端进行交互。代码中包含了错误处理、连接管理和消息传递等功能,适合初学者理解TCP服务器的基本工作原理。
摘要由CSDN通过智能技术生成

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 方式下执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值