PHP swoole TCP服务端和客户端
- 服务端
<?php $server = new swoole_server('127.0.0.1',9501,SWOOLE_PROCESS,SWOOLE_SOCK_TCP); $server->set(array( 'woker_num'=>4, 'max_request'=>1000 )); $server->on('connect',function($serv,$fd,$reactor_id) { echo "接收到来自$reactor_id"."的连接符$fd\n"; }); $server->on('receive',function ($serv,$fd,$reactor_id,$data) { echo "收到{$reactor_id}----{$fd}"."发来的数据$data\n"; $serv->send($fd,"{$reactor_id}---{$fd}发来的数据{$data}"); }); $server->on('close',function ($serv,$fd) { echo "$fd"."关闭\n"; }); $server->start(); ?>
- 客户端
<?php $client = new swoole_client(SWOOLE_SOCK_TCP); if(!$client->connect('127.0.0.1',9501)) { echo "连接失败\n"; exit; } //控制台提示输入: fwrite(STDOUT,"说点儿什么吧\n"); $msg = trim(fgets(STDIN)); $client->send($msg); $ret = $client->recv(); echo $ret; ?>