将Unity3d与Node.js连接

时间:2013-07-10 10:16:22

标签: node.js sockets unity3d

我正在尝试使用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);
    });
});

1 个答案:

答案 0 :(得分:2)

你的活动可能附在错误的顺序上,请尝试这样:

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,因为在大多数情况下它是“黑客”。只有服务器才能做出重要的决定,而不是客户。