我正在尝试为Ratchet WebSocket应用程序添加pecl-pthreads多线程支持。
这是我的应用程序:
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg)
{
$dataIn = json_decode($msg);
switch ($dataIn->type) {
case 'test1':
echo '+t1 block start' . date(' H:i:s') . "\n";
$test1 = new Test1();
$test1->start();
echo '+t1 block end' . date(' H:i:s') . "\n";
break;
case 'test2':
echo '-t2 block start' . date(' H:i:s') . "\n";
$test2 = new Test2();
$test2->start();
echo '-t2 block end' . date(' H:i:s') . "\n";
break;
}
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}这是Test1.php内容:
<?php
namespace MyApp;
class Test1 extends \Thread
{
public function run()
{
echo '#Test1 thread start' . date(' H:i:s') . "\n";
for ($i = 0; $i < 2; $i++) {
echo 1 . date(' H:i:s') . "\n";
sleep(10);
}
echo '#Test1 thread end' . date(' H:i:s') . "\n";
}
}这是Test2.php内容:
<?php
namespace MyApp;
class Test2 extends \Thread
{
public function run()
{
echo '#just Test2 run' . date(' H:i:s') . "\n";
}
}这是JavaScript代码:
var Websocket = new function () {
var ws
this.init = function () {
ws = new WebSocket(wsURL + '/test')
ws.onclose = function () {
setTimeout('Websocket.init()', 1000)
}
}
this.test1 = function () {
var token = {
type: 'test1'
}
ws.send(JSON.stringify(token))
}
this.test2 = function () {
var token = {
type: 'test2'
}
ws.send(JSON.stringify(token))
}
}
$(document).ready(function () {
Websocket.init()
})
var startTest = function () {
Websocket.test2()
Websocket.test2()
Websocket.test1()
Websocket.test2()
Websocket.test2()
}问题是Test1线程阻塞了MyApp的onMessage方法。
当我使用浏览器连接到我的应用程序并运行JavaScript startTest()函数时,我得到以下命令行界面应用程序输出:
-t2 block start 20:08:48
#just Test2 run 20:08:48
-t2 block end 20:08:48
-t2 block start 20:08:48
#just Test2 run 20:08:48
-t2 block end 20:08:48
+t1 block start 20:08:48
#Test1 thread start 20:08:48
+t1 block end 20:08:48
1 20:08:48
1 20:08:58
#Test1 thread end 20:09:08
-t2 block start 20:09:08
#just Test2 run 20:09:08
-t2 block end 20:09:08
-t2 block start 20:09:08
#just Test2 run 20:09:08
-t2 block end 20:09:08正如您所看到的,我从浏览器向我的应用程序发送即时5消息。但是在test1消息之后,onMessage方法的执行会暂停,直到Test1线程的执行结束。是某种pthread/ratchet bug,还是我做错了什么?
发布于 2019-04-18 17:22:36
你在一个连接上发送消息,这意味着你只有一个线程。如果您想检查多线程是否正常工作-您应该尝试在下一个浏览器窗口/选项卡中运行JS。
因为当test1阻塞线程时,其他消息(剩下2条消息test2 )在队列中等待。然而,如果其他人在同一时间连接到服务器,他将不会被阻塞-因为他将获得单独的线程。这就是本例中多线程的强大之处。
https://stackoverflow.com/questions/40940351
复制相似问题