【发布时间】:2021-08-06 20:45:25
【问题描述】:
我有一个棘轮服务器,我尝试通过 Websocket 访问它。它类似于教程:在有新客户端或收到消息时记录。 Ratchet 服务器报告已成功建立连接,而 Kotlin 客户端则没有(Kotlin 中的连接事件从未触发)。我正在使用 socket-io-java 模块 v.2.0.1。客户端在指定的超时时间后显示超时,在服务器上分离并在片刻后再次附加,就像它似乎认为的那样,连接没有正确连接(因为缺少连接响应?)。
如果客户端是 Chrome 的 JS 控制台中的 Websocket-Client,则成功的连接确认会报告给客户端,但不会报告给我的 Kotlin 应用程序。即使是在同一台计算机上运行的 Android 模拟器也没有得到响应(所以我认为问题与 wi-fi 无关)。 连接在 JS 中运行良好,完成了完整的握手,但在 Android 应用中,它只能到达服务器,而不再到达客户端。
这是我的服务器代码:
<?php
namespace agroSMS\Websockets;
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
class SocketConnection implements MessageComponentInterface
{
protected \SplObjectStorage $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
error_log("New client attached");
}
function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
error_log("Client detached");
}
function onError(ConnectionInterface $conn, \Exception $e)
{
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
function onMessage(ConnectionInterface $from, $msg)
{
error_log("Received message: $msg");
// TODO: Implement onMessage() method.
}
}
以及我在终端中运行的脚本:
<?php
use Ratchet\Server\IoServer;
use agroSMS\Websockets\SocketConnection;
use Ratchet\WebSocket\WsServer;
use Ratchet\Http\HttpServer;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new SocketConnection()
)
)
);
$server->run();
我在浏览器中运行的测试(在 Chrome 中返回“已建立连接”,但由于某种原因不在浏览器中“勇敢”):
var conn = new WebSocket('ws://<my-ip>:80');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
我的 Kotlin 代码是什么样子的:
try {
val uri = URI.create("ws://<my-ip>:80")
val options = IO.Options.builder()
.setTimeout(60000)
.setTransports(arrayOf(WebSocket.NAME))
.build()
socket = IO.socket(uri, options)
socket.connect()
.on(Socket.EVENT_CONNECT) {
Log.d(TAG, "[INFO] Connection established")
socket.send(jsonObject)
}
.once(Socket.EVENT_CONNECT_ERROR) {
val itString = gson.toJson(it)
Log.d(TAG, itString)
}
}catch(e : Exception) {
Log.e(TAG, e.toString())
}
一分钟后,Kotlin 代码记录一个“超时”错误,从服务器中分离,然后再次附加。 当我在服务器上停止脚本时,它会给出一个错误:“连接重置,websocket 错误”(这是有道理的,但为什么他没有在第一时间获得连接?)
我还尝试“只是”将 url 中的协议更改为“wss”,以防万一这可能是问题,即使我的服务器甚至无法使用 SSL,但这只是给了我另一个错误:
[{"cause":{"bytesTransferred":0,"detailMessage":"Read timed out","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"websocket error","stackTrace":[],"suppressedExceptions":[]}]
而且连接甚至没有在服务器上建立。所以这次尝试更像是降级。
【问题讨论】:
标签: kotlin websocket socket.io handshake ratchet