-
-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathGame1.cs
More file actions
92 lines (77 loc) 路 2.57 KB
/
Copy pathGame1.cs
File metadata and controls
92 lines (77 loc) 路 2.57 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using NativeWebSocket;
using NativeWebSocket.MonoGame;
namespace MonoGameExample
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private WebSocket _websocket;
private float _sendTimer;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
IsMouseVisible = true;
}
protected override void Initialize()
{
// Install the WebSocket game component.
// This sets up a SynchronizationContext so all WebSocket events
// fire on the game thread automatically.
Components.Add(new WebSocketGameComponent(this));
base.Initialize();
}
protected override async void LoadContent()
{
_websocket = new WebSocket("ws://localhost:3000");
_websocket.OnOpen += () =>
{
Console.WriteLine("Connection open!");
};
_websocket.OnError += (e) =>
{
Console.WriteLine("Error! " + e);
};
_websocket.OnClose += (code) =>
{
Console.WriteLine("Connection closed! Code: " + code);
};
_websocket.OnMessage += (bytes) =>
{
var message = Encoding.UTF8.GetString(bytes);
Console.WriteLine("Received OnMessage! (" + bytes.Length + " bytes) " + message);
};
await _websocket.Connect();
}
protected override async void Update(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// Send a message every 0.3 seconds
if (_websocket?.State == WebSocketState.Open)
{
_sendTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (_sendTimer >= 0.3f)
{
_sendTimer = 0;
// Send binary data
await _websocket.Send(new byte[] { 10, 20, 30 });
// Send text data
await _websocket.SendText("hello from MonoGame!");
}
}
base.Update(gameTime);
}
protected override async void OnExiting(object sender, EventArgs args)
{
if (_websocket != null)
{
await _websocket.Close();
}
base.OnExiting(sender, args);
}
}
}