如何使用 node-red-contrib-socketio 将事件从 Node-Red 发送到 Unity 客户端

How to emit events from Node-Red to a Unity client with node-red-contrib-socketio

我正在尝试使用 node-red-contrib-socketio 包根据 Weather Underground 的输入从 Node-Red 向客户端发出 'weather' 事件。

我在 node-red 函数中使用以下代码来处理来自 WeatherUnderground 的输入并设置事件:

weather = msg.payload.weather;
msg.payload = {weather: weather};
msg.socketIOEvent = 'weather';
RED.util.setMessageProperty(msg, "socketIOEmit", "emit", true);
return msg;

这是设置和发出天气事件的正确方法吗?

供参考:

我已将 SocketIO Out 节点绑定到 Node_Red(因此大概是本地主机上的端口 1880)。我正在使用 Unity 游戏引擎作为客户端,通过资产商店的 Socket.IO 库接收事件:https://assetstore.unity.com/packages/tools/network/socket-io-for-unity-21721

Unity 正在侦听以下 URL 的天气事件:

ws://127.0.0.1:1880/socket.io/?EIO=4&transport=websocket

目前 Unity 似乎正在注册连接,但没有注册发出的天气事件。

我在Unity中处理事件的测试C#脚本如下:

using UnityEngine;
using SocketIO;

public class NodeNetwork : MonoBehaviour
{

    //Reference socket component
    static SocketIOComponent socket;

    void Start()
    {
        //Initialise reference to socket component
        socket = GetComponent<SocketIOComponent>();
        //Register callbacks for network events
        socket.On("open", OnConnected);
        socket.On("weather", OnWeather);
    }

    //Create a callback for the connection
    void OnConnected(SocketIOEvent e)
    {
        Debug.Log("Connected");
        //Emit a move call back to the server 
        socket.Emit("client connected");
    }

    //Create a callback for receipt of weather events
    void OnWeather(SocketIOEvent e)
    {
        Debug.Log("New weather event received" + e.data);
        socket.Emit("weather received");
    }

}

如有任何建议,我们将不胜感激。

从您提供的代码和资产的所有者看来,DEPRECATED SocketIO Unity port, I'd advise you to look into socket.io-unity (which is free from github and 10$ from the asset store) which is a revised version of Quobject's SocketIoClientDotNet 可以使用 Unity3D

我知道这不是解决您的问题的具体答案(除了切换库),但您的包的所有者在 2 年多前曾说过他自己已经停止开发它。因此,为什么我认为将库切换为主要选项会很有趣,我实际上认为你做对了,但它不起作用。我目前在工作,无法对此进行测试,抱歉。我希望我能以某种方式提供帮助。

经过进一步的研究和测试,我得到了这个工作。 Node-Red 流程很好,但某种配置问题阻止了它的工作。重新安装 Node.js 和 Node-Red 解决了问题。

按照@hardillb 的建议使用msg.socketIOEmit = "emit"

我为 Unity 测试了几个 SocketIO 解决方案,最后使用了 SocketIO for Native and WebGL builds by DASPETE,这是一个 10 美元的付费资产。

为了反序列化 JSON,我使用了 SaladLab 的 JSONNetLite Unity package,它是 NewtonSoft.JSon.NET.

的一个分支

要在 Unity WebGL 构建中成功使用该包,您需要将 link.xml file 添加到您的资产文件夹。这为默认的 Unity 字节码剥离添加了例外,它从 DLL 中删除未使用的代码,例如 Newtonsoft.Json 包。

希望对遇到同样问题的你有所帮助。