javascript - Websocket 在客户端断开连接之前不会发送消息
问题描述
我正在使用 PHP 库 Ratchet 学习 WebSocket。但我在从客户端/浏览器发送消息时遇到问题。我尝试过使用 chrome 和 firefox。
在我通过关闭选项卡或刷新浏览器断开客户端连接之前,该消息不会发送到服务器。
更新:我的服务器使用启用了 firewalld 的 Centos 7。
关闭浏览器选项卡后,服务器输出如下:
Connection 73 sending message "tes" to 1 other connection
Connection 73 has disconnected
这是javascript代码:
conn = new WebSocket('ws://websocket.develop.local:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log('ada message');
console.log(e.data);
};
conn.onerror = function(e) {
console.log("WebSocket Error: " , e);
//Custom function for handling errors
//handleErrors(e);
};
function sendMessage(){
var message = document.getElementById("pesan").value;
conn.send(message);
console.log('Sending message: ' + message);
};
这是 PHP 代码(我从 Ratchet 文档中得到的):
<?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) {
// 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();
}
}
解决方案
推荐阅读
- java - Spring-Boot WebMvcTest:如何使用 Authentication 对象参数测试控制器方法?
- scala - Scala:根据预定义数组 Spark 1.6 中存在的列值过滤 DF 行
- perl - PERL 中使用的 exit(0) 和 exit(1) 有什么区别?
- python - 使用 matplotlib 在多线图中显示误差线
- c++ - 未找到响应 libmicrohttpd 的图像
- html - 某个css属性的引入导致其他不相关的属性被忽略
- azure - Azure 数据工厂将 CSV 文件拆分为多个 CSV 文件?
- javascript - 如何在 React 中使用 e.target.name 更新嵌套状态属性
- python - 如何在不结束当前进程的情况下一次关闭所有正在运行的 Jupyter Notebook?
- chef-infra - 让 cookstyle 只检查会导致食谱执行失败的错误