Socket.io 客户端连接但不在 Unity 项目中发出

问题描述 投票:0回答:0

我正在尝试让 socket.io 在 Unity 中工作。

在客户端(Unity)和服务器(Node)上我都可以看到它能够成功连接。

但是,服务器从未收到我在连接时发出的“消息”事件。

我没有看到任何错误。

客户端和服务器都使用socket.io v4.

我使用的是 Unity 版本 2021.3.23f1.

我会注意到,当从 JavaScript 客户端连接到同一台服务器时,一切正常,所以问题似乎出在 Unity 中。

我正在编写的 Unity 库需要这个,所以我不能将付费的 Unity 资产作为依赖项。 例如: https://assetstore.unity.com/packages/tools/network/socket-io-v3-v4-client-basic-standalone-webgl-196557

我尝试了以下 NuGet(通过 NuGetForUnity 安装): https://www.nuget.org/packages/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();
    }
}

我还尝试使用一个统一包,它应该以一种使它与统一一起工作的方式包装上面的库。我得到了完全相同的结果。

https://github.com/itisnajim/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 doesn't work either
        };

        client.OnError += (sender, e) => {
            Debug.Log("OnError: " + e);
        };

        client.Connect();
    }
}

这是节点服务器:

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);
unity3d socket.io
© www.soinside.com 2019 - 2024. All rights reserved.