-
-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathWebSocketExample.cs
More file actions
65 lines (54 loc) · 1.61 KB
/
WebSocketExample.cs
File metadata and controls
65 lines (54 loc) · 1.61 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
using System.Text;
using Godot;
using NativeWebSocket;
/// <summary>
/// Godot has a built-in GodotSynchronizationContext, so all WebSocket
/// events (OnOpen, OnMessage, OnError, OnClose) automatically fire on the main thread.
/// No special integration or DispatchMessageQueue() call is needed.
/// </summary>
public partial class WebSocketExample : Node
{
private WebSocket _websocket;
private double _sendTimer;
public override async void _Ready()
{
_websocket = new WebSocket("ws://localhost:3000");
_websocket.OnOpen += () =>
{
GD.Print("Connection open!");
};
_websocket.OnError += (e) =>
{
GD.Print("Error! " + e);
};
_websocket.OnClose += (code) =>
{
GD.Print("Connection closed! Code: " + code);
};
_websocket.OnMessage += (bytes) =>
{
var message = Encoding.UTF8.GetString(bytes);
GD.Print("Received OnMessage! (" + bytes.Length + " bytes) " + message);
};
await _websocket.Connect();
}
public override async void _Process(double delta)
{
if (_websocket?.State == WebSocketState.Open)
{
_sendTimer += delta;
if (_sendTimer >= 0.3)
{
_sendTimer = 0;
// Send binary data
await _websocket.Send(new byte[] { 10, 20, 30 });
// Send text data
await _websocket.SendText("hello from Godot!");
}
}
}
public override void _ExitTree()
{
_websocket?.Close();
}
}