我在做HTML5遊戲www.titansoftime.com使用PHP P線程與棘輪的WebSocket
我使用棘輪作爲PHP WebSocket的服務器解決方案。它很棒! http://socketo.me/docs/push
我已經做了幾個使用php pthreads擴展的獨立測試,並且看到了一些非常令人興奮的結果。它確實工作並且運作良好..只要websocket不在混合中。
Pthreads給php多線程功能(它真的工作,它是驚人的)。 http://php.net/manual/en/book.pthreads.php
這是我做的:
/src/server.php 這是啓動守護程序文件。
<?php
session_start();
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Pusher;
require __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../mysql.cls.php';
require_once __DIR__ . '/../game.cls.php';
require_once __DIR__ . '/../model.cls.php';
$mysql = new mysql;
$game = new game;
$loop = React\EventLoop\Factory::create();
$pusher = new MyApp\Pusher();
$loop->addPeriodicTimer(0.50, function() use($pusher){
$pusher->load();
});
$webSock = new React\Socket\Server($loop);
if ($loop instanceof \React\EventLoop\LibEventLoop) {
echo "\n HAS LibEvent";
}
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer($pusher)
),
$webSock
);
$loop->run();
這一切工作正常。
/src/MyApp/Pusher.php 該類將數據推送給所有連接的用戶。
<?php
namespace MyApp;
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
class AsyncThread extends \Thread{
public $client;
public function __construct($client){
$this->client = $client;
}
public function run(){
// do work on $this->client
$user = mysql::assoc('SELECT * from users WHERE connection_id = "'.$this->client->resourceId.'"');
// etc..
$this->client->send(json_encode(array('foo'=>'bar')));
}
}
class Pusher implements MessageComponentInterface{
public static $clients = array();
#load
public static function load(){
$client_count = count(self::$clients);
echo "\n\n\n".'Serving to '.$client_count.' clients. '.time();
$start = $istart = microtime(true);
if(!count(self::$clients)){
if(!mysql_ping()){
$game->connect();
}
}
$threads = array();
foreach(self::$clients as $key => $client){
// HANDLE CLIENT
// This works just fine, the only problem is that if I have lets say 50 simultaneous users, the people near the end of the clients array will have to wait till the other users have been processed. This is not desirable
$client->send(json_encode('foo'=>'bar'));
// So I tried this:
$threads[$key] = new AsyncThread($client);
$threads[$key]->start();
// At this point the AsyncThread class will throw a fatal error complaining about not being able to serialize a closure.
// If I dont set "$this->data = $client;" in the thread constructor no error appears but now I cant use the data.
// Also regardless of whether or not I bind the data in the AsyncThread constructor,
// the connection disappears if I call "new AsyncThread($client)". I cannot explain this behavior.
}
}
public function onMessage(ConnectionInterface $from, $msg) {
global $game;
if($msg){
$data = json_decode($msg);
if($data){
switch($data->task){
#connect
case 'connect':
echo "\n".'New connection! ('.$from->resourceId.') '.$from->remoteAddress;
self::$clients[] = $from;
break;
default:
self::closeConnection($from);
echo "\nNO TASK CLOSING";
break;
}
}else{
echo "\n NO DATA";
self::closeConnection($from);
}
}else{
echo "\n NO MSG";
self::closeConnection($from);
}
}
public function closeConnection($conn){
global $game;
if($conn){
if($conn->resourceId){
$connid = $conn->resourceId;
$conn->close();
$new = array();
foreach(self::$clients as $client){
if($client->resourceId != $connid){
$new[] = $client;
}
}
self::$clients = $new;
$game->query('UPDATE users set connection_id = 0 WHERE connection_id = "'.intval($connid).'" LIMIT 1');
echo "\n".'Connection '.$connid.' has disconnected';
}
}
}
public function onClose(ConnectionInterface $conn) {
echo "\nCLIENT DROPPED";
self::closeConnection($conn);
}
public function onOpen(ConnectionInterface $conn) {
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "\nCLIENT ERRORED";
self::closeConnection($conn);
}
public function onSubscribe(ConnectionInterface $conn, $topic) {
}
public function onUnSubscribe(ConnectionInterface $conn, $topic) {
}
public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {
}
public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {
}
}
只要不在事件循環中創建線程,這一切都可以正常工作。
我是這樣做的錯誤方式或者是php多線程和websockets不兼容?
霍布斯你有這個問題的更新? – 2014-10-27 15:03:18
我還在等待答案哈哈。 – Hobbes 2014-10-27 15:11:36
我不認爲有必要實現多線程,如果你通過棘輪和反應的來源,那麼你就會明白,它正在使用無阻塞套接字讀取功能。另外,如果你想要少量的性能提升,那麼你可能需要考慮一下libevent。 – 2014-11-07 14:40:19