-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebSocketChatClient.cs
52 lines (44 loc) · 1.15 KB
/
WebSocketChatClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using UnityEngine;
using WebSocketSharp;
public class WebSocketChatClient : MonoBehaviour
{
private WebSocket ws;
void Start()
{
// Connect to the server
ws = new WebSocket("ws://localhost:8080/");
ws.OnMessage += (sender, e) =>
{
if (e.IsText)
{
Debug.Log("Message from the server: " + e.Data);
}
else if (e.IsBinary)
{
// Decode the byte array to string
string decodedMessage = System.Text.Encoding.UTF8.GetString(e.RawData);
Debug.Log("Message from the server: " + decodedMessage);
}
};
ws.Connect();
// Send a message to the server
ws.Send("Hello, server! I'm an Unity client.");
}
void OnDestroy()
{
if (ws != null)
{
ws.Close();
ws = null;
}
}
// Send a message to the server
public void SendMessageToServer(string message)
{
if (ws.IsAlive)
{
ws.Send(message);
}
}
}