Note
This fork optimized the GC Alloc.
This is the simplest and easiest WebSocket library for Unity you can find!
- No external DLL's required (uses built-in
System.Net.WebSockets) - WebGL/HTML5 support
- Supports all major build targets
- Very simple API
- (Used in Colyseus Unity SDK)
Requires Unity 2019.1+ with .NET 4.x+ Runtime
- Open Unity
- Open Package Manager Window
- Click Add Package From Git URL
- Enter URL:
https://github.com/endel/NativeWebSocket.git#upm
- Download this project
- Copy the sources from
NativeWebSocket/Assets/WebSocketinto yourAssetsdirectory.
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingNativeWebSocket;publicclassConnection:MonoBehaviour{WebSocketwebsocket;// Start is called before the first frame updateasyncvoidStart(){websocket=newWebSocket("ws://localhost:3000");websocket.OnOpen+=()=>{Debug.Log("Connection open!");};websocket.OnError+=(e)=>{Debug.Log("Error! "+e);};websocket.OnClose+=(e)=>{Debug.Log("Connection closed!");};websocket.OnMessage+=(bytes)=>{Debug.Log("OnMessage!");Debug.Log(bytes);// getting the message as a string// var message = System.Text.Encoding.UTF8.GetString(bytes);// Debug.Log("OnMessage! " + message);};// Keep sending messages at every 0.3sInvokeRepeating("SendWebSocketMessage",0.0f,0.3f);// waiting for messagesawaitwebsocket.Connect();}voidUpdate(){
#if !UNITY_WEBGL||UNITY_EDITORwebsocket.DispatchMessageQueue();
#endif
}asyncvoidSendWebSocketMessage(){if(websocket.State==WebSocketState.Open){// Sending bytesawaitwebsocket.Send(newbyte[]{10,20,30});// Sending plain textawaitwebsocket.SendText("plain text message");}}privateasyncvoidOnApplicationQuit(){awaitwebsocket.Close();}}1. Start the local WebSocket server:
cd Server
npm install
npm start
2. Open the NativeWebSocket/Assets/WebSocketExample/WebSocketExampleScene.unity on Unity and Run.
Big thanks to Jiri Hybek. This implementation is based on his work.
Apache 2.0
