Shepherd0619 / UnityWebSocketUtility

A script serves as template of WebSocket in Unity.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

UnityWebSocketUtility

A script serves as template of WebSocket in Unity.

WebSocketUtility is a utility class written in C# for Unity that provides functionality for establishing and managing WebSocket connections. It allows sending and receiving messages over the WebSocket protocol.

Features

  • Connect to a WebSocket server using a specified URI.
  • Send messages to the server.
  • Receive messages from the server.
  • Handle received JSON data.
  • Implement heartbeat functionality to check the connection status.

Usage

  1. Create an instance of the WebSocketUtility class by providing the WebSocket server URI.
Uri serverUri = new Uri("wss://example.com");
WebSocketUtility wsUtility = new WebSocketUtility(serverUri);
  1. Connect to the WebSocket server.
wsUtility.Connect();
  1. Send messages to the server.
string message = "Hello, server!";
wsUtility.Send(message);
  1. Handle received JSON datab by subscribing to the OnReceiveJson event. registering callback with protocol.
wsUtility.RegisterProtocolCallback("HELLO_WORLD", HelloWorld);

private void HelloWorld(string data)
{
    // Process the received JSON data
}
  1. Disconnect from the WebSocket server.
wsUtility.Disconnect();

Dependencies

  • UnityEngine
  • System.Net.WebSockets
  • System.Text
  • System.Threading
  • SimpleJSON
  • Newtonsoft.Json
  • OverwatchLogger

Tips

  1. You may notice HttpManager (from Biozone.Networking). It's just an empty Monobehaviour whose mission is host coroutines. You can replace it with your own.

About

A script serves as template of WebSocket in Unity.

License:BSD 3-Clause "New" or "Revised" License


Languages

Language:C# 100.0%