Created
October 4, 2017 17:07
-
-
Save amantix/40b7050947aa784dead3306584ad9d3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net; | |
using System.Net.WebSockets; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace WebTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var listener = new HttpListener(); | |
listener.Prefixes.Add("http://localhost:8080/"); | |
listener.Start(); | |
Task.Run(async () => | |
{ | |
while (true) | |
{ | |
var ctx = await listener.GetContextAsync(); | |
if (ctx.Request.IsWebSocketRequest) | |
Task.Factory.StartNew(() => WebSocketHandle(ctx)); | |
} | |
}).Wait(); | |
} | |
public async static void WebSocketHandle(HttpListenerContext context) | |
{ | |
WebSocketContext webSocketContext = null; | |
try | |
{ | |
webSocketContext = await context.AcceptWebSocketAsync(subProtocol: null); | |
var ipAddress = context.Request.UserHostAddress.ToString(); | |
Console.WriteLine($"Connected: {ipAddress}"); | |
} | |
catch (Exception e) | |
{ | |
context.Response.StatusCode = 500; | |
context.Response.Close(); | |
Console.WriteLine($"Exception: {e}"); | |
return; | |
} | |
WebSocket webSocket = webSocketContext.WebSocket; | |
try | |
{ | |
byte[] receiveBuffer = new byte[1024]; | |
while(webSocket.State==WebSocketState.Open) | |
{ | |
var receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None); | |
if (receiveResult.MessageType == WebSocketMessageType.Close) | |
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); | |
else | |
await webSocket.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, receiveResult.Count), WebSocketMessageType.Text, receiveResult.EndOfMessage, CancellationToken.None); | |
} | |
} | |
catch(Exception e) | |
{ | |
Console.WriteLine($"Exception: {e}"); | |
} | |
finally | |
{ | |
if (webSocket != null) | |
webSocket.Dispose(); | |
Console.WriteLine($"Disconnected"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment