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.
- Create a JavaScript file which defines the functions you need and implements them by calling native browser functionality.
- Give it the file extension
.jslib - Put it into the directiory
Assets/Pluginsof your Unity project - 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.