dongxia9519
2017-03-07 09:50
浏览 38

如何使用php创建异步套接字服务器?

I'm trying to create a Asynchronous socket server to handle socket client, send message to client when it's needs. I use reactphp library to implement it but I can't do correct, my server still is blocked. I'm new in this library, please help.

require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$socket->on('connection', function ($conn) {
    $conn->pipe($conn);
});
echo "Socket server listening on port 4000.
";
echo "You can connect to it by running: telnet localhost 4000
";
$socket->listen(4200);
$loop->run();


// code bottom doesn't run because of blocking socket

图片转代码服务由CSDN问答提供 功能建议

我正在尝试创建一个异步套接字服务器来处理套接字客户端,在需要时向客户端发送消息。 我使用 reactphp库来实现它,但我做不到,我的服务器仍然被阻止。 我是这个库的新手,请帮忙。

  require'ports / autoload.php'; 
 $ loop = React \ EventLoop \ Factory :: create();  
 $ socket = new React \ Socket \ Server($ loop); 
 $ socket-> on('connection',function($ conn){
 $ conn-> pipe($ conn); 
  }}; 
echo“套接字服务器侦听端口4000. 
”; 
echo“你可以通过运行连接到它:telnet localhost 4000 
”; 
 $ socket-> listen(4200); 
 $  loop-> run(); 
 
 
 //由于阻塞套接字而无法运行代码底部
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsf12313 2017-03-12 12:17

    $loop->run(); runs the event loop and will never return unless you stop the loop. The loop is your scheduler and invokes your event handlers in case events occur.

    If you want to react to events, you have to register event listeners before you run the loop.

    点赞 评论

相关推荐 更多相似问题