I want to connect to a socket server from Unity’s WebGL build.
When I use C#'s Socket class, I was able to connect to a socket server in the Unity editor.
But it did a WebGL build and gave an error when run in the browser.
SocketException: Success
at System.Net.Sockets.Socket..ctor (System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) [0x00000] in <00000000000000000000000000000000>:0
--- End of stack trace from previous location where exception was thrown ---```
I found in this article that I have to use WebSockets.
https://discussions.unity.com/t/758524
How can I actually implement it using WebSockets?
If possible, it would be very helpful if you could share a sample.
Thank you.
Raw sockets are not available on WebGL since browsers do not offer any API to access them. As you found out, you’ll need to use WebSockets, but that means writing your application with a WebSocket library, not with the .NET socket API. You can use libraries like websocket-sharp for that. Unity’s transport package also supports WebSockets starting with its 2.0.1 version (only available on 2022.2 and later).
If you decide to use some library based on websocket, here’s an option you can try: azure web pubsub transport, which is also support webgl platform. Here’s the quick setup video (2 min):