I wrote a simple WebSocketServer, which I found out on the MSDN web-site. But it doesn't work. Can you explain me how I should to run this simple project, because I launch it but nothing happened.
Server
namespace WebSocketServer { class Program { static void Main(string[] args) { var task1 = Run(); // Console.ReadLine(); } public static async Task Run() { HttpListener s = new HttpListener(); s.Prefixes.Add("http://localhost:8000/ws"); s.Start(); var hc = await s.GetContextAsync(); if (!hc.Request.IsWebSocketRequest) { hc.Response.StatusCode = 400; hc.Response.Close(); return; } var wsc = await hc.AcceptWebSocketAsync(null); var ws = wsc.WebSocket; for (int i = 0; i != 10; ++i) { // await Task.Delay(20); var time = DateTime.Now.ToLongTimeString(); var buffer = Encoding.UTF8.GetBytes(time); var segment = new ArraySegment<byte>(buffer); await ws.SendAsync(segment, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None); } await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None); } } }
Client
namespace WebSocketClient { class Program { static void Main(string[] args) { var clientTask1 = Client(); Console.ReadLine(); } static async Task Client() { ClientWebSocket ws = new ClientWebSocket(); var uri = new Uri("ws://localhost:8000/ws/"); await ws.ConnectAsync(uri, CancellationToken.None); var buffer = new byte[1024]; while (true) { var segment = new ArraySegment<byte>(buffer); var result = await ws.ReceiveAsync(segment, CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { await ws.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "I don't do binary", CancellationToken.None); return; } int count = result.Count; while (!result.EndOfMessage) { if (count >= buffer.Length) { await ws.CloseAsync(WebSocketCloseStatus.InvalidPayloadData, "That's too long", CancellationToken.None); return; } segment = new ArraySegment<byte>(buffer, count, buffer.Length - count); result = await ws.ReceiveAsync(segment, CancellationToken.None); count += result.Count; } var message = Encoding.UTF8.GetString(buffer, 0, count); Console.WriteLine(">" + message); } } } } And I need to create a simple web-site, which will be take some data (For example Time) from WebSocketServer and show it on this page. I wrote some code, but nothing is going on
<html> <body> <script type ="text/javascript"> var ws = new WebSocket("ws://localhost:8000/ws/"); ws.onmessage = function (args) { var time = args.data; }; </script> </body> </html>