Unity中Socket.io客户端连接成功但无法发送事件的问题
Unity Socket.IO 客户端发送事件无响应问题解决
我在Unity 2021.3.23f1中使用Socket.IO v4,客户端(Unity)和Node服务器均显示连接成功,但服务器始终接收不到客户端在连接时发送的"message"事件,且无任何错误提示。用JavaScript客户端连接同一服务器时一切正常,问题应出在Unity端。由于正在编写Unity库,无法依赖付费资源,我尝试了通过NuGetForUnity安装的SocketIOClient NuGet包,以及封装该库的SocketIOUnity Unity包,结果完全一致。
Unity测试代码(SocketIOClient)
using System.Threading.Tasks; using UnityEngine; using SocketIOClient; public class Test : MonoBehaviour { void Start() { Connect(); } async Task Connect() { var client = new SocketIO("ws://localhost:8090"); client.OnConnected += async (sender, e) => { Debug.Log("OnConnected: " + e); await client.EmitAsync("message", "bla"); }; client.OnError += (sender, e) => { Debug.Log("OnError: " + e); }; await client.ConnectAsync(); } }
Unity测试代码(SocketIOUnity)
using UnityEngine; using System; public class Test : MonoBehaviour { void Start() { var uri = new Uri("ws://localhost:8090"); var client = new SocketIOUnity(uri); client.OnConnected += async (sender, e) => { Debug.Log("OnConnected"); await client.EmitAsync("message", "bla"); // client.Emit 同样无效 }; client.OnError += (sender, e) => { Debug.Log("OnError: " + e); }; client.Connect(); } }
Node服务器原代码
const httpServer = require("http").createServer(); const io = require("socket.io")(httpServer, { cors: true }); io.on("connection", (socket) => { console.log("connection"); }); io.on("message", (value) => { console.log("message", value); }); httpServer.listen(8090);
问题根源与修复
问题不在Unity端,而是Node服务器的事件监听方式错误。Socket.IO中,客户端发送的事件是绑定到单个连接会话的socket实例上的,而非全局的io对象。原代码中io.on("message")无法捕获客户端发送的事件,必须在connection回调中针对每个socket实例监听事件。
修正后的Node服务器代码:
const httpServer = require("http").createServer(); const io = require("socket.io")(httpServer, { cors: true }); io.on("connection", (socket) => { console.log("connection"); // 在此处监听单个socket连接的message事件 socket.on("message", (value) => { console.log("message", value); }); }); httpServer.listen(8090);
这样修改后,服务器就能正常接收Unity客户端发送的"message"事件了。
内容的提问来源于stack exchange,提问作者Royi Bernthal
相关产品推荐
相关产品推荐

