Search code examples
unity-game-enginewebsockettcptcpserverunity-webgl

Connect to TCP server with WebGL Unity


I have a TCP server (which I can not change/modify) running which sends data and I want it to connect to Unity WebGL build.So first of all I know it is natively not supported to connect to a TCP server in WebGL. I searched for workarounds and tried the following : Use Websockify to enable connection from the TCP server to a WebSocket. I used the NativeWebsocket Library but it would not connect to the server unfortunately. I also read about these blogs :

How to let a Unity WebGL build connect to a local python server?

https://forum.unity.com/threads/webgl-tcp-client.738419/

But they didn't really help either. Has anyone tried this or knows how to make it work (if it is even possible :) )? Thanks in advance


Solution

  • Unity3D uses the .NET C# libraries, so even though Unity doesn't explicitly provide a TCP library, you can still use .NET's TCP APIs. It's worth noting that not all platforms will support this, for example, WebGL doesn't support TCP communication.

    See the example in .NET documentation for help on implementation: System.Net.Sockets TcpClient

    For WebGL, it is impossible to use TCP communication, so you'll have to wrap the server in some kind of HTTP/Websockets transport - you cannot leave the server as is, it will not work because the protocol cannot be communicated with for security reasons.

    If you have any question as to the specifics of implementation, feel free to ask in the comments - I don't have enough information to elaborate further on your specific application