-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cs
108 lines (92 loc) · 3.41 KB
/
Server.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
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace Telex
{
public class Server
{
private readonly TcpListener listener;
private uint guidCounter;
private readonly ConcurrentDictionary<uint, Connection> connections = new();
private readonly Channel<Message> receiveChannel = Channel.CreateUnbounded<Message>(new UnboundedChannelOptions() { SingleReader = true });
private readonly Channel<ArraySegment<byte>> broadcastChannel = Channel.CreateUnbounded<ArraySegment<byte>>(new UnboundedChannelOptions() { SingleReader = true });
private int messageCounter;
public int totalMessages = 0;
public Server(ushort port)
{
listener = new TcpListener(IPAddress.Any, port);
listener.Server.NoDelay = true;
}
public void Start()
{
listener.Start();
_ = Task.Run(() => ListenAsync());
_ = Task.Run(() => BroadcastAsync());
}
private async ValueTask ListenAsync()
{
while (true)
{
var client = await listener.AcceptTcpClientAsync().ConfigureAwait(false);
client.NoDelay = true;
uint guid = NextGuid();
connections[guid] = new Connection(client, guid, receiveChannel);
await receiveChannel.Writer.WriteAsync(new Message { Type = EventType.Connect, Guid = guid });
}
}
uint NextGuid() => Interlocked.Increment(ref guidCounter);
public void Broadcast(ArraySegment<byte> segment)
{
broadcastChannel.Writer.TryWrite(segment);
}
private async ValueTask BroadcastAsync()
{
while (true)
{
var segment = await broadcastChannel.Reader.ReadAsync().ConfigureAwait(false);
foreach (Connection connection in connections.Values)
{
connection.SendSync(segment);
}
Pack.Recycle(segment);
}
}
public bool SendTo(uint guid, ArraySegment<byte> segment)
{
if (connections.ContainsKey(guid))
{
connections[guid].Send(segment);
return true;
}
return false;
}
// implement throttling method for processing x amount of messages, default is 100 per cycle (might be overkill)
public bool NextMessage(out Message message, int maxMessages = 100)
{
message = default; // basically set message to null
// only process maxMessages this cycle
if (messageCounter >= maxMessages)
{
messageCounter = 0;
return false;
}
// we have a valid message
if (receiveChannel.Reader.TryRead(out message))
{
totalMessages++;
messageCounter++;
return true;
}
// no messages this cycle, reset everything
messageCounter = 0;
return false;
}
public void Tick(int numProcMessage)
{
}
}
}