Skip to main content
3 of 3
added 1 character in body
Philipp
  • 123.2k
  • 28
  • 264
  • 345

As the documentation says, The Unity scripting API does not expose direct WebSocket access itself. But you can access the native web browser API by calling JavaScript from Unity C# scripts.

  1. Create a JavaScript file which defines the functions you need and implements them by calling native browser functionality.
  2. Give it the file extension .jslib
  3. Put it into the directiory Assets/Plugins of your Unity project
  4. Import them into a C# script by defining a class-level method with the prefix [DllImport("__Internal")] private static extern.

Example for a websocket.jslib:

mergeInto(LibraryManager.library, {

  WebSocketInit: function(url, protocol) {
         this.socket = new WebSocket(url, protocol);
  },
  WebSocketSend: function(message) {
         this.socket.send(message);
  }

});

Example of a C# script using those methods:

using UnityEngine;
using System.Runtime.InteropServices;

public class WebSocketSender : MonoBehaviour {

    [DllImport("__Internal")]
    private static extern void WebSocketInit(string url, string protocol);

    [DllImport("__Internal")]
    private static extern void WebSocketSend(string message);

    void Start() {
        WebSocketInit("wss://example.com/gameserver", "mygameprotocol");
    }
    
    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
                WebSocketSend("Pew!Pew!Pew!");
        }
    }
}

But please keep in mind that WebSockets are not native TCP/IP sockets. The protocol adds some framing and masking to the messages which makes them unable to implement any raw TCP/IP protocols. So you won't be able to use WebSockets to interface with any server which doesn't implement the WebService protocol.

Philipp
  • 123.2k
  • 28
  • 264
  • 345