by
12
8
3,045
5
Top 1% !
Popular
Famous
Nice
Easy-to-find
Specified
Refined
MultiPlatform
Popularity: 4671st place
ClassNameEKOSocket
InputName0cntxt
InputType0HttpContext
Languagecsharp
MethodNameOnRequest
OutputTypevoid

EKOING C# WebSokETS server Thangy

it might work
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/565840/EKOING-C--WebSokETS-server-Thangy?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
using System; using System.Web; using System.Net.WebSockets; using System.Web.WebSockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; public class EKOSocket : IHttpHandler { private const int MaxBuffer = 64 * 1024; public void OnRequest (HttpContext cntxt) { try { cntxt.AcceptWebSocketRequest(async wsContext => { try { WebSocket skt = wsContext.WebSocket; byte[] received = new byte[MaxBuffer]; ArraySegment<byte> buff = new ArraySegment<byte>(receive); string clientMsg; if (skt.State == WebSocketState.Open) { var announce = "Connection @ : " + DateTime.Now.ToString(); ArraySegment<byte> output2 = new ArraySegment<byte>(Encoding.UTF8.GetBytes(announce)); await skt.SendAsync(output2, WebSocketMessageType.Text, true, CancellationToken.None); } while (skt.State == WebSocketState.Open) { WebSocketReceiveResult receive = await skt.ReceiveAsync(buff, CancellationToken.None); if (receive.MessageType == WebSocketMessageType.Close) { // EKO back await skt.CloseAsync( receive.CloseStatus.GetValueOrDefault(), receive.CloseStatusDescription, CancellationToken.None); return; } int offset = receive.Count; while (receive.EndOfMessage == false) { receive = await skt.ReceiveAsync(new ArraySegment<byte>(received, offset, MaxBuffer - offset),CancellationToken.None); offset += received.Count; } if (receive.MessageType == WebSocketMessageType.Text) { string cmd = Encoding.UTF8.GetString(received, 0, offset); clientMsg = cmd; clientMsg = "EKO: \"" + clientMsg + "\""; ArraySegment<byte> output = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userString)); await skt.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None); } else if (receive.MessageType == WebSocketMessageType.Binary) { clientMsg = String.Format("binary message received, size={0} bytes", receiveResult.Count); ArraySegment<byte> output = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userString)); await skt.SendAsync(output, WebSocketMessageType.Text, true, CancellationToken.None); } } } catch (Exception ex) { // do something with the exception } }); } catch (Exception ex) { cntxt.Response.StatusCode = 500; cntxt.Response.StatusDescription = ex.Message; cntxt.Response.End(); } } public bool canRecycle { get { return false; } } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus