forked from aspnet/WebSockets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
58 lines (49 loc) · 2 KB
/
Copy pathProgram.cs
File metadata and controls
58 lines (49 loc) · 2 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestServer
{
class Program
{
static void Main(string[] args)
{
RunEchoServer().Wait();
}
private static async Task RunEchoServer()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:12345/");
listener.Start();
Console.WriteLine("Started");
while (true)
{
HttpListenerContext context = listener.GetContext();
if (!context.Request.IsWebSocketRequest)
{
context.Response.Close();
continue;
}
Console.WriteLine("Accepted");
var wsContext = await context.AcceptWebSocketAsync(null);
var webSocket = wsContext.WebSocket;
byte[] buffer = new byte[1024];
WebSocketReceiveResult received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (received.MessageType != WebSocketMessageType.Close)
{
// Console.WriteLine("Echo, " + received.Count + ", " + received.MessageType + ", " + received.EndOfMessage);
// Echo anything we receive
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, received.Count), received.MessageType, received.EndOfMessage, CancellationToken.None);
received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(received.CloseStatus.Value, received.CloseStatusDescription, CancellationToken.None);
webSocket.Dispose();
Console.WriteLine("Finished");
}
}
}
}