gpt4 book ai didi

node.js - 将 Unity3d 与 Node.js 连接起来

转载 作者:搜寻专家 更新时间:2023-10-31 22:34:35 25 4
gpt4 key购买 nike

我正在尝试使用 socket.io 将我的 unity3d 程序连接到 node.js 服务器。

使用UnitySocketIO,我成功连接了客户端和服务器。

但是,On 或 Emit 方法不起作用。

谁能帮我解决这个问题?

void Start () {

string socketUrl = "http://127.0.0.1:50122";
Debug.Log("socket url: " + socketUrl);

this.socket = new Client(socketUrl);
this.socket.Opened += this.SocketOpened;
this.socket.Message += this.SocketMessage;
this.socket.SocketConnectionClosed += this.SocketConnectionClosed;
this.socket.Error += this.SocketError;

this.socket.Connect();
}

private void SocketOpened (object sender, EventArgs e) {
Debug.Log("socket opened"); // i got this message
this.socket.On ("message", (data) => {
Debug.Log ("message : " + data);
});
this.socket.Emit("join", "abc");
Debug.Log("Emit done"); // i got this message
}

....

io.sockets.on('connection', function (socket) {

console.log('connect'); // i got this message

socket.emit('message', 'Hello World!');

socket.on('join', function (id) {
console.log('client joined with id ' + id);
socket.emit('message', 'Hello ' + id);
});
});

最佳答案

您的事件可能以错误的顺序附加,尝试这样:

void Start() {
string socketUrl = "http://127.0.0.1:50122";
Debug.Log("socket url: " + socketUrl);

this.socket = new Client(socketUrl);
this.socket.Opened += this.SocketOpened;
this.socket.Message += this.SocketMessage;
this.socket.SocketConnectionClosed += this.SocketConnectionClosed;
this.socket.Error += this.SocketError;

this.socket.On("message", (data) => {
Debug.Log("message: " + data);
});

this.socket.Connect();
}

对于 Node :

io.sockets.on('connection', function(socket) {
console.log('client connected');
socket.emit('message', 'Hello World!');
});

也不要让客户决定自己的 ID,因为在大多数情况下它是“可破解的”。只有服务器应该做出重要决定,而不是客户端。

关于node.js - 将 Unity3d 与 Node.js 连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17568066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com