Search Unity

Resolved I want to connect to a socket server from Unity's WebGL build.

Discussion in 'Multiplayer' started by unitsume, May 2, 2023.

  1. unitsume

    unitsume

    Joined:
    Oct 7, 2022
    Posts:
    31
    Hello.

    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.

    build.framework.js.gz:3
    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://forum.unity.com/threads/getting-socket-exception-in-unity-webgl.746276/

    How can I actually implement it using WebSockets?
    If possible, it would be very helpful if you could share a sample.

    Thank you.
     
  2. simon-lemay-unity

    simon-lemay-unity

    Unity Technologies

    Joined:
    Jul 19, 2021
    Posts:
    441
    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).
     
  3. unitsume

    unitsume

    Joined:
    Oct 7, 2022
    Posts:
    31
    I see! I understand!
    Thank you for your politeness.
    I was saved.

    I'll check how to use websocket-sharpya and Unity Transport.
     
  4. wanlwanl

    wanlwanl

    Joined:
    Jul 7, 2022
    Posts:
    7
    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):
     
  5. adamgolden

    adamgolden

    Joined:
    Jun 17, 2019
    Posts:
    1,555
    Another option is PieSocket. Free tier available. Reasonably simple to implement via jslib. API docs.