【发布时间】:2019-12-06 07:11:38
【问题描述】:
在我的 Android 项目中,我想实现 Web Sockets。所以首先我尝试集成服务器端的 Websockets 并尝试在命令行中对其进行测试。以下链接显示了我如何尝试打开 Web Socket 连接。我试图到达在 Web 套接字连接中创建的端口并且它有效!但是当我附加一条消息时,我从未收到它。可能是因为没有触发onMessage函数?
https://i.stack.imgur.com/N8tsf.jpg
此外,我使用以下代码打开 Websocket 连接并发送消息。
?php
ini_set('display_errors',1);
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require_once '/var/www/vendor/autoload.php';
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
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');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
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";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8081
);
$server->run();
?>
如果我运行 php app.php,则没有任何错误。那么实际上它应该可以发送消息并接收它吗?此外,似乎没有触发 onMessage 功能。但是如果我在公共函数 __construct() 函数中添加一个回显,它会被打印出来,所以它可能是唯一被执行的函数。
希望有人能帮我在这个 Web Socket Connection 中接收和打印消息。
感谢您的帮助!
【问题讨论】:
-
如果开始执行 php app.php 不会出现错误。函数 _construct() 似乎是唯一被触发的函数