PHP异步调用socket实现是一种提高代码性能的方法,能够同时处理多个客户端请求,提高服务器的吞吐量。下面是实现这种方式的完整攻略:
一、安装需要的扩展
-
安装swoole扩展
pecl install swoole
-
安装event扩展
pecl install event
二、实现异步socket服务端
在服务端代码中,需要使用swoole与event两个扩展库创建异步socket服务器。
$serv = new swoole_server("127.0.0.1", 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
$serv->set(array(
'worker_num' => 4,
'daemonize' => false,
'max_request' => 1000,
'dispatch_mode' => 2,
));
$serv->on('Connect', function ($serv, $fd){
echo "Client: Connect.\n";
});
$serv->on('Receive', function ($serv, $fd, $from_id, $data){
$conn = new EventBufferEvent($serv->eventBase, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);
$conn->setCallbacks(
function ($bev, $events) {
$bev->free();
},
function ($bev, $data) use ($fd, $serv) {
$serv->send($fd, "Server:".$data);
$bev->write($data);
},
function ($bev, $events) use ($fd, $serv) {
$serv->close($fd);
$bev->free();
}
);
$conn->enable(Event::READ | Event::WRITE);
$conn->write($data);
});
$serv->on('Close', function ($serv, $fd){
echo "Client: Close.\n";
});
$serv->start();
其中创建EventBufferEvent并设置回调函数是实现异步的关键。
三、实现异步socket客户端
在客户端代码中,也需要使用swoole与event两个扩展库创建异步socket客户端。
$fp = stream_socket_client('tcp://127.0.0.1:9501', $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, "Hello world!\n");
echo fread($fp, 1024);
fclose($fp);
}
客户端与服务端的区别在于客户端socket不需要加入事件循环中使用。
四、示例
下面是一个实现异步socket服务的实例:
<?php
$serv = new swoole_server("127.0.0.1", 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
$serv->set(array(
'worker_num' => 4,
'daemonize' => false,
'max_request' => 1000,
'dispatch_mode' => 2,
));
$serv->on('Connect', function ($serv, $fd){
echo "Client: Connect.\n";
});
$serv->on('Receive', function ($serv, $fd, $from_id, $data){
$conn = new EventBufferEvent($serv->eventBase, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);
$conn->setCallbacks(
function ($bev, $events) {
$bev->free();
},
function ($bev, $data) use ($fd, $serv) {
$serv->send($fd, "Server:".$data);
$bev->write($data);
},
function ($bev, $events) use ($fd, $serv) {
$serv->close($fd);
$bev->free();
}
);
$conn->enable(Event::READ | Event::WRITE);
$conn->write($data);
});
$serv->on('Close', function ($serv, $fd){
echo "Client: Close.\n";
});
$serv->start();
下面是一个实现异步socket客户端的实例:
<?php
$client = new swoole_client(SWOOLE_TCP | SWOOLE_ASYNC);
$client->on("connect", function($cli) {
$cli->send("hello from client 1");
});
$client->on("receive", function($cli, $data){
echo "received data: $data";
});
$client->on("error", function($cli){
echo "connect failed\n";
});
$client->on("close", function($cli){
echo "connection close\n";
});
$client->connect("127.0.0.1", 9501);
以上示例展示了PHP异步调用socket实现代码的完整攻略,可以在需要提高代码性能的情况下使用。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:PHP异步调用socket实现代码 - Python技术站