forked from vtortola/WebSocketListener
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Program.cs
172 lines (145 loc) · 6.29 KB
/
Program.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
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using log4net.Config;
using vtortola.WebSockets;
using vtortola.WebSockets.Deflate;
using vtortola.WebSockets.Rfc6455;
namespace WebSocketListenerTests.Echo
{
class Program
{
private static readonly Log4NetLogger Log = new Log4NetLogger(typeof(Program));
private static void Main(string[] args)
{
// configuring logging
XmlConfigurator.Configure();
Log.Warning("Starting Echo Server");
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
var cancellation = new CancellationTokenSource();
var bufferSize = 1024 * 8; // 8KiB
var bufferPoolSize = 100 * bufferSize; // 800KiB pool
var options = new WebSocketListenerOptions
{
SubProtocols = new[] { "text" },
PingTimeout = TimeSpan.FromSeconds(5),
NegotiationTimeout = TimeSpan.FromSeconds(5),
PingMode = PingMode.Manual,
ParallelNegotiations = 16,
NegotiationQueueCapacity = 256,
SendBufferSize = bufferSize,
BufferManager = BufferManager.CreateBufferManager(bufferPoolSize, bufferSize),
Logger = Log
};
options.Standards.RegisterRfc6455(factory =>
{
factory.MessageExtensions.RegisterDeflateCompression();
});
// configure tcp transport
options.Transports.ConfigureTcp(tcp =>
{
tcp.BacklogSize = 100; // max pending connections waiting to be accepted
tcp.ReceiveBufferSize = bufferSize;
tcp.SendBufferSize = bufferSize;
});
// adding the WSS extension
//var certificate = new X509Certificate2(File.ReadAllBytes("<PATH-TO-CERTIFICATE>"), "<PASSWORD>");
// options.ConnectionExtensions.RegisterSecureConnection(certificate);
var listenEndPoints = new Uri[] {
new Uri("ws://localhost") // will listen both IPv4 and IPv6
};
// starting the server
var server = new WebSocketListener(listenEndPoints, options);
server.StartAsync().Wait();
Log.Warning("Echo Server listening: " + string.Join(", ", Array.ConvertAll(listenEndPoints, e => e.ToString())) + ".");
Log.Warning("You can test echo server at http://www.websocket.org/echo.html.");
var acceptingTask = AcceptWebSocketsAsync(server, cancellation.Token);
Log.Warning("Press any key to stop.");
Console.ReadKey(true);
Log.Warning("Server stopping.");
cancellation.Cancel();
server.StopAsync().Wait();
acceptingTask.Wait();
}
private static async Task AcceptWebSocketsAsync(WebSocketListener server, CancellationToken cancellation)
{
await Task.Yield();
while (!cancellation.IsCancellationRequested)
{
try
{
var webSocket = await server.AcceptWebSocketAsync(cancellation).ConfigureAwait(false);
if (webSocket == null)
{
if (cancellation.IsCancellationRequested || !server.IsStarted)
break; // stopped
continue; // retry
}
#pragma warning disable 4014
EchoAllIncomingMessagesAsync(webSocket, cancellation);
#pragma warning restore 4014
}
catch (OperationCanceledException)
{
/* server is stopped */
break;
}
catch (Exception acceptError)
{
Log.Error("An error occurred while accepting client.", acceptError);
}
}
Log.Warning("Server has stopped accepting new clients.");
}
private static async Task EchoAllIncomingMessagesAsync(WebSocket webSocket, CancellationToken cancellation)
{
Log.Warning("Client '" + webSocket.RemoteEndpoint + "' connected.");
var sw = new Stopwatch();
try
{
while (webSocket.IsConnected && !cancellation.IsCancellationRequested)
{
try
{
var messageText = await webSocket.ReadStringAsync(cancellation).ConfigureAwait(false);
if (messageText == null)
break; // webSocket is disconnected
sw.Restart();
await webSocket.WriteStringAsync(messageText, cancellation).ConfigureAwait(false);
Log.Warning("Client '" + webSocket.RemoteEndpoint + "' sent: " + messageText + ".");
sw.Stop();
}
catch (TaskCanceledException)
{
break;
}
catch (Exception readWriteError)
{
Log.Error("An error occurred while reading/writing echo message.", readWriteError);
break;
}
}
// close socket before dispose
await webSocket.CloseAsync(WebSocketCloseReason.NormalClose);
}
finally
{
// always dispose socket after use
webSocket.Dispose();
Log.Warning("Client '" + webSocket.RemoteEndpoint + "' disconnected.");
}
}
private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
Log.Error("Unobserved Exception: ", e.Exception);
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Log.Error("Unhandled Exception: ", e.ExceptionObject as Exception);
}
}
}