socket.io-client-csharp icon indicating copy to clipboard operation
socket.io-client-csharp copied to clipboard

Socket.io client connects but doesn't emit in a Unity project

Open royibernthal opened this issue 2 years ago • 2 comments

I'm trying to get socket.io to work in Unity.

On both the client (Unity) and the server (Node) I can see that it was able to connect successfully.

However, the server never receives the "message" event that I'm emitting upon connection.

I don't see any errors.

using System.Threading.Tasks;
using UnityEngine;
using SocketIOClient;

public class Test : MonoBehaviour
{
    void Start() {
        Connect();
    }

    async Task Connect()
    {
        var client = new SocketIO("ws://localhost:8090");

        client.OnConnected += async (sender, e) =>
        {
            Debug.Log("OnConnected: " + e);

            await client.EmitAsync("message", "bla");
        };

        client.OnError += (sender, e) => {
            Debug.Log("OnError: " + e);
        };

        await client.ConnectAsync();
    }
}

Here's the Node server:

const httpServer = require("http").createServer();

const io = require("socket.io")(httpServer, { cors: true });

io.on("connection", (socket) => {
    console.log("connection");
});

io.on("message", (value) => {
    console.log("message", value);
});

httpServer.listen(8090);

royibernthal avatar Apr 18 '23 18:04 royibernthal

IDK if this will work but you should try changing the port. Just guessing though, I don't know what causes this.

You may have to open port 8090 yourself or use another one if another program is using it.

Use this tool to make sure the port is open on both machines: https://portchecker.co/checking

And if all else fails, there is a wrapper for unity: https://github.com/itisnajim/SocketIOUnity I haven't tested it though so it may not work.

Exilon24 avatar Apr 27 '23 07:04 Exilon24

Change your server's connection listener to have the message listener:

io.on("connection", (socket) => {
    console.log("connection");
    socket.on("message", (value) => {
        console.log("message", value);
    });
});

Troy-Dev avatar May 10 '23 02:05 Troy-Dev