Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting Unity3d with Node.js

I am trying to use socket.io to connect my unity3d program with node.js server.

Using the UnitySocketIO, I succeeded the connection between the client and server.

However, On or Emit method does not work.

Can someone help me with this problem?

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);
    });
});
like image 569
user1957032 Avatar asked Jul 10 '13 10:07

user1957032


1 Answers

Your event probably attached in wrong order, try like this:

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();
}

And for node:

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

As well do not allow client to decide own ID, as it is "hackable" in most cases. Only server should make important decisions and not client.

like image 59
moka Avatar answered Oct 03 '22 05:10

moka