socket.io-client-csharp
socket.io-client-csharp copied to clipboard
Socket.io client connects but doesn't emit in a Unity project
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);
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.
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);
});
});