Created
February 11, 2025 00:14
-
-
Save kadiryumlu/4c3b1dfe780318516842794f2c29fc6d to your computer and use it in GitHub Desktop.
Server Sent Events Client for Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Server Sent Events Client for Unity | |
*/ | |
using System.IO; | |
using System.Net.Http; | |
using System.Threading; | |
using UnityEngine; | |
using UnityEngine.Events; | |
public class SSEClient : MonoBehaviour | |
{ | |
[SerializeField] bool autoStart = false; | |
[SerializeField] string url; | |
public UnityEvent<string, string> OnEvent; | |
public UnityEvent<string> OnMessage; | |
private Thread thread; | |
private void OnEnable() | |
{ | |
if(autoStart) | |
{ | |
Run(); | |
} | |
} | |
private void OnDisable() | |
{ | |
if (autoStart) | |
{ | |
Stop(); | |
} | |
} | |
public void Run() | |
{ | |
thread = new Thread(CreateWebRequestLoop); | |
thread.Start(); | |
} | |
public void Stop() | |
{ | |
if(thread != null) | |
{ | |
thread.Abort(); | |
} | |
} | |
private void CreateWebRequestLoop() | |
{ | |
using (HttpClient client = new HttpClient()) | |
{ | |
client.DefaultRequestHeaders.Add("Accept", "text/event-stream"); | |
using (Stream stream = client.GetStreamAsync(url).Result) | |
{ | |
using (StreamReader reader = new StreamReader(stream)) | |
{ | |
string evnt = string.Empty; | |
string data = string.Empty; | |
while (!reader.EndOfStream) | |
{ | |
//Debug.Log(reader.ReadLine()); | |
string line = reader.ReadLine(); | |
//Debug.Log(line); | |
if (line.StartsWith("event:")) | |
{ | |
evnt = line.Substring(6).Trim(); | |
} | |
if (line.StartsWith("data:")) | |
{ | |
data = line.Substring(5).Trim(); | |
RaiseEvent(evnt, data); | |
} | |
if (line.Trim().Equals(string.Empty)) | |
{ | |
evnt = string.Empty; | |
data = string.Empty; | |
} | |
} | |
} | |
} | |
} | |
} | |
private void RaiseEvent(string name, string data) | |
{ | |
Debug.Log($"event: {name}, data: {data}"); | |
if(name == null) | |
{ | |
OnMessage?.Invoke(data); | |
} | |
else | |
{ | |
OnEvent?.Invoke(name, data); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment