Skip to content

Repository files navigation

Native WebSocket

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)

Consider supporting my work on Patreon | Ko-fi | PayPal

Support me on Patreon

Installation

Requires Unity 2019.1+ with .NET 4.x+ Runtime

Install via UPM (Unity Package Manager)

  1. Open Unity
  2. Open Package Manager Window
  3. Click Add Package From Git URL
  4. Enter URL: https://github.com/endel/NativeWebSocket.git#upm

Install manually

  1. Download this project
  2. Copy the sources from NativeWebSocket/Assets/WebSocket into your Assets directory.

Usage

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();}}

Demonstration

1. Start the local WebSocket server:

cd Server
npm install
npm start

2. Open the NativeWebSocket/Assets/WebSocketExample/WebSocketExampleScene.unity on Unity and Run.

Acknowledgements

Big thanks to Jiri Hybek. This implementation is based on his work.

License

Apache 2.0

About

🔌 WebSocket client for Unity - with no external dependencies (WebGL, Native, Android, iOS, UWP)

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages