我正在尝试为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()
}
问题是测试1线程阻塞了MyApp的onMessage方法。
当我使用浏览器连接到我的应用程序并运行JavaScript startTest()函数时,我得到此CLI应用程序输出:
-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线程执行结束。它是某种pthreads /棘轮错误还是我做错了什么?
您在一个连接上发送消息,这意味着您只有一个线程。如果您想检查多线程是否正常工作 - 您应该尝试在下一个浏览器窗口/选项卡中运行该JS。
当test1阻塞线程时,Cuz,否则消息(2个消息test2 left)正在队列中等待。但是,如果其他人将同时连接到服务器,他将不会被阻止 - 因为他将获得单独的线程。在这种情况下,这就是多线程的强大功能。