forked from cbluoss/OpenHacknet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultiplayerLobby.cs
368 lines (353 loc) · 13.5 KB
/
MultiplayerLobby.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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Hacknet.Gui;
using Hacknet.Magic;
using Microsoft.Xna.Framework;
namespace Hacknet
{
internal class MultiplayerLobby : GameScreen
{
public static List<string> allLocalIPs = new List<string>();
private byte[] buffer;
private TcpClient chatclient;
private NetworkStream chatclientStream;
private string chatIP = "";
private TcpClient client;
private NetworkStream clientStream;
private bool connectingToServer;
private readonly Color dark_ish_gray = new Color(20, 20, 20);
private readonly Color darkgrey = new Color(9, 9, 9);
private string destination = "192.168.1.1";
private ASCIIEncoding encoder;
private string externalIP = "Loading...";
private Rectangle fullscreen;
private bool isConnecting;
private TcpListener listener;
private Thread listenerThread;
private List<string> messages;
private string messageString = "Test Message";
private string myIP = "?";
private bool shouldAddServer;
public MultiplayerLobby()
{
TransitionOnTime = TimeSpan.FromSeconds(0.1);
TransitionOffTime = TimeSpan.FromSeconds(0.3);
}
public override void LoadContent()
{
base.LoadContent();
try
{
listener = new TcpListener(IPAddress.Any, Multiplayer.PORT);
listener.Start();
listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener);
buffer = new byte[4096];
encoder = new ASCIIEncoding();
if (allLocalIPs.Count == 0)
{
myIP = getLocalIP();
new Thread(getExternalIP).Start();
Console.WriteLine("Started Multiplayer IP Getter Thread");
}
else
myIP = allLocalIPs[0];
messages = new List<string>();
var viewport = ScreenManager.GraphicsDevice.Viewport;
fullscreen = new Rectangle(0, 0, viewport.Width, viewport.Height);
}
catch (Exception ex)
{
ScreenManager.RemoveScreen(this);
ScreenManager.AddScreen(new MainMenu(), ScreenManager.controllingPlayer);
}
}
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (!shouldAddServer || ScreenState == ScreenState.TransitionOff)
return;
ExitScreen();
ScreenManager.AddScreen(new OS(client, clientStream, true, ScreenManager), ScreenManager.controllingPlayer);
if (chatclient == null)
return;
chatclient.Close();
}
public override void HandleInput(InputState input)
{
base.HandleInput(input);
GuiData.doInput(input);
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
GuiData.startDraw();
ScreenManager.SpriteBatch.Draw(Utils.white, fullscreen, isConnecting ? Color.Gray : Color.Black);
doGui();
GuiData.endDraw();
ScreenManager.FadeBackBufferToBlack(byte.MaxValue - TransitionAlpha);
}
public void drawConnectingGui()
{
PatternDrawer.draw(new Rectangle(100, 200, 600, 250), 1.4f, Color.DarkGreen*0.3f, Color.DarkGreen,
GuiData.spriteBatch);
TextItem.doLabel(new Vector2(110f, 210f), "Connecting...", new Color?());
}
public void doGui()
{
PatternDrawer.draw(new Rectangle(180, 160, 500, 85), 1f, darkgrey, dark_ish_gray, GuiData.spriteBatch);
TextItem.doSmallLabel(new Vector2(200f, 170f), "IP To Connect to:", new Color?());
destination = TextBox.doTextBox(100, 200, 200, 300, 1, destination, GuiData.smallfont);
if (Button.doButton(123, 510, 201, 120, 23, "Connect", new Color?()) || TextBox.BoxWasActivated)
{
ConnectToServer(destination);
}
else
{
if (isConnecting)
drawConnectingGui();
TextItem.doLabel(new Vector2(200f, 300f), "Local IPs: " + myIP, new Color?());
var y = 340f;
for (var index = 0; index < allLocalIPs.Count - 1; ++index)
{
TextItem.doLabel(new Vector2(351f, y), allLocalIPs[index], new Color?());
y += 40f;
}
TextItem.doLabel(new Vector2(200f, y + 40f), "Extrn IP: " + externalIP, new Color?());
var pos = new Vector2(610f, 280f);
TextItem.doLabel(pos, "Info:", new Color?());
pos.Y += 40f;
var text =
DisplayModule.cleanSplitForWidth(
"To Begin a multiplayer session, type in the IP of the computer you want to connect to and press enter or connect. Both players must be on this screen. To connect over the internet, use the extern IP address and ensure port 3030 is open.",
400);
TextItem.doFontLabel(pos, text, GuiData.tinyfont, Color.DarkGray, float.MaxValue, float.MaxValue);
if (!Button.doButton(999, 10, 10, 200, 30, "<- Back to Menu", Color.Gray))
return;
ExitScreen();
ScreenManager.AddScreen(new MainMenu(), ScreenManager.controllingPlayer);
}
}
public void ConnectToServer(string ip)
{
connectingToServer = true;
try
{
var socket = new TcpClient();
var remoteEP = new IPEndPoint(IPAddress.Parse(ip), Multiplayer.PORT);
socket.Connect(remoteEP);
var stream = socket.GetStream();
buffer = encoder.GetBytes("connect Client Connecting");
stream.Write(buffer, 0, buffer.Length);
stream.Flush();
stream.Read(buffer, 0, buffer.Length);
ExitScreen();
ScreenManager.AddScreen(new OS(socket, stream, false, ScreenManager), ScreenManager.controllingPlayer);
}
catch (Exception ex)
{
DebugLog.add(ex.ToString());
isConnecting = false;
}
}
public void chatToServer(string ip, string msg)
{
try
{
if (chatclientStream == null)
{
chatclient = new TcpClient();
chatclient.Connect(new IPEndPoint(IPAddress.Parse(ip), Multiplayer.PORT));
chatclientStream = chatclient.GetStream();
}
buffer = encoder.GetBytes("Chat " + msg);
messages.Add("Me: " + msg);
chatclientStream.Write(buffer, 0, buffer.Length);
chatclientStream.Flush();
messageString = "";
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
public void DoAcceptTcpClientCallback(IAsyncResult ar)
{
var tcpListener = (TcpListener) ar.AsyncState;
try
{
client = tcpListener.EndAcceptTcpClient(ar);
clientStream = client.GetStream();
var flag = true;
while (flag)
{
var num = 0;
try
{
num = clientStream.Read(buffer, 0, 4096);
}
catch (Exception ex)
{
Console.WriteLine(ex);
if (Game1.threadsExiting)
break;
}
if (num == 0)
{
client.Close();
if (Game1.threadsExiting)
break;
}
var @string = encoder.GetString(buffer);
var chArray1 = new char[1]
{
' '
};
if (@string.Split(chArray1)[0].Equals("Chat"))
{
var chArray2 = new char[3]
{
' ',
'\n',
char.MinValue
};
messages.Add(@string.Substring(4).Trim(chArray2).Replace("\0", ""));
if (Game1.threadsExiting)
break;
}
else
{
buffer = encoder.GetBytes("Replying - Hello World");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
shouldAddServer = true;
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void listenForConnections()
{
try
{
listener = new TcpListener(IPAddress.Any, Multiplayer.PORT);
listener.Start();
client = listener.AcceptTcpClient();
clientStream = client.GetStream();
var flag = true;
while (flag)
{
var num = 0;
try
{
num = clientStream.Read(buffer, 0, 4096);
}
catch (Exception ex)
{
Console.WriteLine(ex);
if (Game1.threadsExiting)
break;
}
if (num == 0)
{
client.Close();
if (Game1.threadsExiting)
break;
}
var @string = encoder.GetString(buffer);
var chArray1 = new char[1]
{
' '
};
if (@string.Split(chArray1)[0].Equals("Chat"))
{
var chArray2 = new char[3]
{
' ',
'\n',
char.MinValue
};
messages.Add(@string.Substring(4).Trim(chArray2).Replace("\0", ""));
if (Game1.threadsExiting)
break;
}
else
{
buffer = encoder.GetBytes("Replying - Hello World");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
shouldAddServer = true;
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
public static string getLocalIP()
{
var str = "?";
foreach (var ipAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
str = ipAddress.ToString();
allLocalIPs.Add(ipAddress.ToString());
}
}
return str;
}
public void getExternalIPwithPF()
{
try
{
externalIP = "Attempting automated port-fowarding...";
try
{
if (NAT.Discover())
{
Console.WriteLine("Attempting port foward");
NAT.ForwardPort(Multiplayer.PORT, ProtocolType.Tcp, "Hacknet (TCP)");
externalIP = NAT.GetExternalIP().ToString();
}
else
ScreenManager.ShowPopup("You dont have UPNP enabled - Internet play will not work");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
if (!externalIP.Equals("Attempting automated port-fowarding..."))
return;
externalIP = "Automated port-fowarding Failed - Internet Play Disabled";
}
catch (Exception ex)
{
Console.WriteLine(ex);
externalIP = "Automated port-fowarding Failed - Internet Play Disabled";
}
}
public void getExternalIP()
{
try
{
externalIP = "Unknown...";
externalIP = new WebClient().DownloadString("http://icanhazip.com/");
}
catch (Exception ex)
{
Console.WriteLine(ex);
externalIP = "Could not Find Conection";
}
}
}
}