如何使用 WebSocket 向 Socket.io 服务器发送消息 [英] How to send a message with WebSocket to a Socket.io server

查看:107
本文介绍了如何使用 WebSocket 向 Socket.io 服务器发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 React Native 应用程序,我想使用 WebSocket 类与我的 Socket.io 服务器进行通信.

I'm developing a React Native application and I want to use the WebSocket class to communicate with my Socket.io server.

我可以很好地连接到服务器,但是我在使用 .send() 方法向它发送消息时遇到了问题.

I can connect to the server just fine, but I'm having problems sending messages to it using the .send() method.

我在 React Native 上试过这个:

I tried this on React Native:

var socket = new WebSocket("ws://host:port/socket.io/?transport=websocket");
socket.onopen = () => {
    console.log("connected");
    socket.send('data');
 };

在我的 Socket.io 服务器上,我创建了一个专门用于测试的侦听器:

On my Socket.io server I have this listener that I created just for testing:

socket.on('data', function(data) {
  console.log("data");
})

连接确实有效,我也可以在服务器上看到它.但是当我执行 socket.send('data') 时,会在服务器上调用 disconnect 事件,而不是我上面写的 data 事件.(我通过使用函数调用 .send() 方法对此进行了测试,因此这确实会导致服务器断开连接)

The connection does work, and I'm able to see that on the server too. But when I do socket.send('data') the disconnect event gets called on the server rather than the data event I wrote above. (I tested this by using a function to call the .send() method, so this does cause a disconnect on the server)

有人可以对此有所了解吗?

Can anyone shine some light on this?

推荐答案

那是因为 Socket.io 与 WebSocket 不完全兼容 - 有初始握手,连接回退(例如,当没有可用的 WS 时,使用 AJAX 长池或其他技术)以及 Socket.io 向您隐藏的其他东西,以使您的生活更轻松.本质上,Socket.io 应该被视为一个单独的协议.

That's because Socket.io is not exactly compatible with WebSocket - there are initial handshakes, connection fallbacks (eg. when no WS is available, use AJAX long pooling or other technique) and other things that Socket.io hides from you to make your life easier. Essentially, Socket.io should be seen as a separate protocol.

要连接到 Socket.io 服务器,您必须使用 Socket.io 客户端库.

To connect to a Socket.io server, you have to use Socket.io client library.

这篇关于如何使用 WebSocket 向 Socket.io 服务器发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆