This repository was archived by the owner on Jun 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathUdpListener.cs
More file actions
100 lines (88 loc) · 3.24 KB
/
Copy pathUdpListener.cs
File metadata and controls
100 lines (88 loc) · 3.24 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
93
94
95
96
97
98
99
100
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using TheP0ngServer.Models;
namespace TheP0ngServer.ProtocolManagers
{
public class UdpListener
{
private static LoggerService logger;
private static int _udpPort;
private static System.Timers.Timer _timer;
private static string _apiDomain;
private static int _gameServicePort;
public static async void StartUdpListening(int port, string APIdomain, int GameServicePort)
{
logger = new LoggerService();
_udpPort = port;
_apiDomain = APIdomain;
_gameServicePort = GameServicePort;
UdpClient listener = new UdpClient(_udpPort);
IPEndPoint groupEndPoint = new IPEndPoint(IPAddress.Any, _udpPort);
logger.LogInformation($"Started UDP Listening on {_udpPort}");
try
{
TcpClient client = new TcpClient();
client.Connect(_apiDomain, GameServicePort);
StreamWriter stream = new StreamWriter(client.GetStream());
logger.LogInformation("Connected TCP with webAPI");
await SendPacket(new Packet(Meta.Connect, "router"), stream);
while (true)
{
byte[] bytes = listener.Receive(ref groupEndPoint);
int movement = Convert.ToInt32(bytes[0]);
var finalMsg = movement + " " + Configs.SchoolCode;
await SendPacket(new Packet(Meta.Message, finalMsg), stream);
}
}
catch(Exception e)
{
logger.LogError($"Exception: {e}");
}
finally
{
listener.Close();
Restart();
}
}
public static async Task SendPacket(Packet packet, StreamWriter stream)
{
await stream.WriteAsync(packet.ToJson());
await stream.FlushAsync();
}
private static void Restart()
{
_timer = new System.Timers.Timer();
logger.LogInformation("Restarting UDP server in 5 seconds");
_timer.Interval = 5000;
_timer.Elapsed += OnTimedEvent;
_timer.AutoReset = false;
_timer.Enabled = true;
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
StartUdpListening(_udpPort, _apiDomain, _gameServicePort);
}
private void SendMessageToWebAPI(string message, string ip, int port) {
//MAYBE used in future
try
{
TcpClient client = new TcpClient();
client.Connect(ip, port);
logger.LogInformation("Connected TCP with webAPI");
var stream = client.GetStream();
byte[] bytes = Encoding.ASCII.GetBytes(message);
stream.Write(bytes, 0, bytes.Length);
stream.Close();
client.Close();
}
catch (SocketException e)
{
logger.LogError($"SocketException: {e}");
}
}
}
}