连接Unity3d与Node.js
我正在尝试使用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(); }
而对于节点:
io.sockets.on('connection', function(socket) { console.log('client connected'); socket.emit('message', 'Hello World!'); });
同样,不允许客户自己决定自己的ID,因为在大多数情况下它是“可破解的”。 只有服务器应该做出重要决定而不是客户端。