-
-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathConnection.cs
More file actions
75 lines (63 loc) · 1.88 KB
/
Connection.cs
File metadata and controls
75 lines (63 loc) · 1.88 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System.Text;
using UnityEngine;
using NativeWebSocket;
/// <summary>
/// Unity example — attach this script to a GameObject in your scene.
///
/// Setup:
/// 1. Import NativeWebSocket via UPM:
/// Window > Package Manager > "+" > Add package from git URL:
/// https://github.com/endel/NativeWebSocket.git#upm
///
/// 2. Create an empty GameObject and attach this script.
///
/// 3. Start the test server: cd NodeServer && npm install && node index.js
///
/// 4. Press Play.
///
/// Unity's UnitySynchronizationContext handles event dispatching automatically,
/// so no DispatchMessageQueue() call is needed in Update().
/// </summary>
public class Connection : MonoBehaviour
{
WebSocket websocket;
async void Start()
{
Application.runInBackground = true;
websocket = new WebSocket("ws://localhost:3000");
websocket.OnOpen += () =>
{
Debug.Log("Connection open!");
};
websocket.OnError += (e) =>
{
Debug.Log("Error! " + e);
};
websocket.OnClose += (code) =>
{
Debug.Log("Connection closed! Code: " + code);
};
websocket.OnMessage += (bytes) =>
{
var message = Encoding.UTF8.GetString(bytes);
Debug.Log("Received OnMessage! (" + bytes.Length + " bytes) " + message);
};
// Send messages every 0.3 seconds
InvokeRepeating("SendWebSocketMessage", 0.0f, 0.3f);
await websocket.Connect();
}
async void SendWebSocketMessage()
{
if (websocket.State == WebSocketState.Open)
{
// Send binary data
await websocket.Send(new byte[] { 10, 20, 30 });
// Send text data
await websocket.SendText("hello from Unity!");
}
}
private async void OnApplicationQuit()
{
await websocket.Close();
}
}