php - 制作一个多线程 websocket
问题描述
我使用棘轮和 php 制作了一个 Websocket 服务器,它工作正常,但问题是它不是多线程的,当多个客户端同时向服务器发送消息时,这会使服务器重播延迟。我想知道是否有任何方法可以使其成为多线程,以便每个连接都在它自己的线程上运行,或者如果它不是正确的方法,请给我一个更好的方法谢谢!
Chat.php 代码:
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require 'vendor/autoload.php';
require(dirname(dirname(__FILE__)).'/inc/class/class-app_api.php');
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
echo 'server Started!';
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n", $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
$obj = new \app_api($from, $msg);
$res = $obj->handleRequest();
if (is_array($res)) {
foreach ($this->clients as $client) {
if ($from != $client) {
// The sender is not the receiver, send to each client connected
$client->send($res['data']);
}
}
}else {
$from->send($res);
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$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";
$obj = new \venicehost_app_api($from);
$conn->send($obj->setError('An error has occurred:' . $e->getMessage()));
//$conn->close();
}
}
?>
Server.php 代码:
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require_once("Chat.php");
//require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
port,
ip address
);
$server->run();
?>
解决方案
推荐阅读
- php - 如果我将它作为字符串存储在变量中,我可以调用条带库吗?
- node.js - 为原型函数添加类型
- android - 使用 buildozer 打包我的 kivy 应用程序时如何修复“java.lang.module.FindException:找不到模块 java.se.ee”错误
- javascript - 解析复杂的 Json 字符串
- android - 当我的 android 手机连接到本地网络之外的网络时,我的 android 应用程序(使用我的 pc 作为服务器)无法工作
- pdf - Burst 和 cat 后 pdf 的大小增加十倍(使用 pdftk)
- python - 我无法在我的烧瓶应用程序中正确引发异常
- tableau-api - Tableau 在导入时将我的数字四舍五入到小数点后 16 位。我怎样才能阻止这个?
- c++ - Qchart,legend()->setGeometry 不起作用
- c++ - 从 C++ 输出中删除逗号