javascript - 在 Tabris.js 中使用 Websocket api 连接到 socket.io 服务器

标签 javascript websocket socket.io tabris

我正在尝试为 android 构建一个 Tabris 应用程序,充当我的 socket.io 服务器的客户端。我正在阅读一些内容,发现 tabris.js 支持 WebSocket API,因此我尝试连接到我的套接字。像这样的io服务器

var socket = new WebSocket('ws://159.89.92.113:4343');

但我收到此错误

WebSocket 协议(protocol)也是一个字符串或字符串数​​组

然后我尝试用我唯一能想到的东西来填写该参数

var socket = new WebSocket('ws://159.89.92.113:4343', 'ws');

然后我收到此错误

当 WebSocket 状态为 CONNECTING 时无法“发送”WebSocket 消息

老实说,我不知道如何完成这项工作,我尝试了很多不同的方法。

最佳答案

关于 protocols 参数,WHATWG Standard 的内容如下:不得不说:

protocols is either a string or an array of strings. If it is a string, it is equivalent to an array consisting of just that string; if it is omitted, it is equivalent to the empty array. Each string in the array is a subprotocol name. The connection will only be established if the server reports that it has selected one of these subprotocols. The subprotocol names have to match the requirements for elements that comprise the value of Sec-WebSocket-Protocol fields as defined by The WebSocket protocol.

因此,请引用您的服务器的实现,了解该参数发送的内容(如果有的话)。

<小时/>

连接时不应出现“WebSocket 状态为 CONNECTING 时无法‘发送’WebSocket 消息”消息,但如果您尝试过早发送,则很可能会出现这种情况; the message特别是在连接阶段调用 send() 时发生。您可以延迟发送消息,直到建立连接,如下所示:

const socket = new WebSocket('ws://159.89.92.113:4343'); 
socket.onopen = (event) => {
    socket.send('Hello World');
};
<小时/>

最后,这是一个使用 Tabris.js 应用程序作为带有 Websocket 服务器的客户端的 WebSocket 设置的端到端工作示例:

https://github.com/eclipsesource/tabris-js/tree/2.x/examples/web-socket

简单地说:

git clone https://github.com/eclipsesource/tabris-js
cd tabris-js
git checkout 2.x
cd examples/web-socket
npm install
tabris serve

并在另一个窗口中从同一目录启动服务器npm run server

*请注意,这是为 Tabris.js 2.x 编写的,因此您可以使用 2.x 客户端或 migrate it to 3.x 来测试它。 .

关于javascript - 在 Tabris.js 中使用 Websocket api 连接到 socket.io 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58721504/

相关文章:

java - Spring websocket - 来自集群的 sendToUser 无法从备份服务器工作

websocket - Mqtt 连接为 aws IOT 预签名 URL 提供 403

sockets - 如何配置Logstash 2.3.3 WebSocket

node.js - 有人可以读取使用 socket.io 发送的对象,即使它没有在前端为用户打印出来

javascript - 解析 Promise 以更新多行

javascript - Socket.io 连接始终为 false

javascript - 在 javascript 中创建 cloudant View 时如何转义冒号和其他特殊字符

Javascript 使用相对字符串路径遍历另一个字符串路径

javascript - 有没有在 node.js 中做实时模型的框架?

node.js - 使用 Nodejs 和 Socket IO 的多人游戏