public override WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList<ArraySegment<byte>> data) { var total = data.Sum(d => d.Count); var payloadLength = context.PayloadLength; var text = Encoding.UTF8.GetString(data, total - payloadLength, payloadLength); return new WebSocketPackageInfo(text, ServiceProvider.StringParser); }
// As server internal WebSocket(HttpListenerWebSocketContext context, string protocol) { _context = context; _protocol = protocol; _closeContext = context.Close; _secure = context.IsSecureConnection; _stream = context.Stream; init(); }
private static RTCPeerConnection Createpc(WebSocketContext context) { List <RTCCertificate> presetCertificates = null; if (File.Exists(LOCALHOST_CERTIFICATE_PATH)) { var localhostCert = new X509Certificate2(LOCALHOST_CERTIFICATE_PATH, (string)null, X509KeyStorageFlags.Exportable); presetCertificates = new List <RTCCertificate> { new RTCCertificate { Certificate = localhostCert } }; } RTCConfiguration pcConfiguration = new RTCConfiguration { certificates = presetCertificates, X_RemoteSignallingAddress = context.UserEndPoint.Address, iceServers = new List <RTCIceServer> { new RTCIceServer { urls = SIPSORCERY_STUN_SERVER, username = SIPSORCERY_STUN_SERVER_USERNAME, credential = SIPSORCERY_STUN_SERVER_PASSWORD, credentialType = RTCIceCredentialType.password } }, iceTransportPolicy = RTCIceTransportPolicy.all }; var pc = new RTCPeerConnection(pcConfiguration); // Add inactive audio and video tracks. MediaStreamTrack audioTrack = new MediaStreamTrack(SDPMediaTypesEnum.audio, false, new List <SDPMediaFormat> { new SDPMediaFormat(SDPMediaFormatsEnum.PCMU) }, MediaStreamStatusEnum.RecvOnly); pc.addTrack(audioTrack); MediaStreamTrack videoTrack = new MediaStreamTrack(SDPMediaTypesEnum.video, false, new List <SDPMediaFormat> { new SDPMediaFormat(SDPMediaFormatsEnum.VP8) }, MediaStreamStatusEnum.Inactive); pc.addTrack(videoTrack); pc.onicecandidateerror += (candidate, error) => logger.LogWarning($"Error adding remote ICE candidate. {error} {candidate}"); pc.onconnectionstatechange += (state) => logger.LogDebug($"Peer connection state changed to {state}."); pc.OnReceiveReport += (type, rtcp) => logger.LogDebug($"RTCP {type} report received."); pc.OnRtcpBye += (reason) => logger.LogDebug($"RTCP BYE receive, reason: {(string.IsNullOrWhiteSpace(reason) ? "<none>" : reason)}."); pc.onicecandidate += (candidate) => { if (pc.signalingState == RTCSignalingState.have_local_offer || pc.signalingState == RTCSignalingState.have_remote_offer) { context.WebSocket.Send($"candidate:{candidate}"); } }; // Peer ICE connection state changes are for ICE events such as the STUN checks completing. pc.oniceconnectionstatechange += (state) => { logger.LogDebug($"ICE connection state change to {state}."); }; return(pc); }
internal WebSocket(TcpListenerWebSocketContext context) : this() { _uri = context.Path.ToUri(); _context = context; _tcpClient = context.Client; _wsStream = context.Stream; _endPoint = context.ServerEndPoint; _isClient = false; _isSecure = context.IsSecureConnection; }
internal void Start(WebSocketContext context, WebSocketSessionManager sessions) { if (_websocket != null) { _websocket.Log.Error ("This session has already been started."); context.WebSocket.Close (HttpStatusCode.ServiceUnavailable); return; } _context = context; _sessions = sessions; _websocket = context.WebSocket; _websocket.CustomHandshakeRequestChecker = checkIfValidConnectionRequest; _websocket.EmitOnPing = _emitOnPing; _websocket.IgnoreExtensions = _ignoreExtensions; _websocket.Protocol = _protocol; var waitTime = sessions.WaitTime; if (waitTime != _websocket.WaitTime) _websocket.WaitTime = waitTime; _websocket.OnOpen += onOpen; _websocket.OnMessage += onMessage; _websocket.OnError += onError; _websocket.OnClose += onClose; _websocket.ConnectAsServer (); }
// As server private void releaseServerResources () { if (_closeContext == null) return; _closeContext (); _closeContext = null; _stream = null; _context = null; }
// As server private void init(WebSocketContext context) { _context = context; _uri = context.Path.ToUri (); _secure = context.IsSecureConnection; _client = false; }
internal void Bind(WebSocketContext context, WebSocketServiceManager sessions) { if (IsBound) return; _context = context; _sessions = sessions; _websocket = context.WebSocket; _websocket.CookiesValidation = ValidateCookies; _websocket.OnOpen += onOpen; _websocket.OnMessage += onMessage; _websocket.OnError += onError; _websocket.OnClose += onClose; IsBound = true; }
public virtual void ExecuteResult(WebSocketContext context) { }
public override WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList<ArraySegment<byte>> data) { return new WebSocketPackageInfo(data, ServiceProvider.BinaryDataParser, ServiceProvider.StringParser); }
/// <summary> /// Called when this WebSockets Server accepts a new WebSockets client. /// </summary> /// <param name="context">The context.</param> protected override void OnClientConnected(WebSocketContext context) { var process = new Process() { EnableRaisingEvents = true, StartInfo = new ProcessStartInfo() { CreateNoWindow = true, ErrorDialog = false, FileName = "cmd.exe", RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false, WorkingDirectory = "c:\\" } }; process.OutputDataReceived += (s, e) => { lock (SyncRoot) { if ((s as Process).HasExited) { return; } var ws = FindContext(s as Process); if (ws != null && ws.WebSocket.State == WebSocketState.Open) { this.Send(ws, e.Data); } } }; process.ErrorDataReceived += (s, e) => { lock (SyncRoot) { if ((s as Process).HasExited) { return; } var ws = FindContext(s as Process); if (ws != null && ws.WebSocket.State == WebSocketState.Open) { this.Send(ws, e.Data); } } }; process.Exited += (s, e) => { lock (SyncRoot) { var ws = FindContext(s as Process); if (ws != null && ws.WebSocket.State == WebSocketState.Open) { ws.WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Process exited", CancellationToken.None).GetAwaiter().GetResult(); } } }; // add the process to the context lock (SyncRoot) { Processes[context] = process; } process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); }
public static RequestHandshake Parse(WebSocketContext context) { return new RequestHandshake { Headers = context.Headers, HttpMethod = "GET", RequestUri = context.RequestUri, ProtocolVersion = HttpVersion.Version11 }; }
internal void StartSession(WebSocketContext context) { var session = CreateSession (); session.Start (context, Sessions); }
// As server private string checkIfValidHandshakeRequest(WebSocketContext context) { var headers = context.Headers; return !context.IsWebSocketRequest ? "Not WebSocket connection request." : !validateHostHeader (headers ["Host"]) ? "Invalid Host header." : !validateSecWebSocketKeyHeader (headers ["Sec-WebSocket-Key"]) ? "Invalid Sec-WebSocket-Key header." : !validateSecWebSocketVersionClientHeader (headers ["Sec-WebSocket-Version"]) ? "Invalid Sec-WebSocket-Version header." : !validateCookies (context.CookieCollection, _cookies) ? "Invalid Cookies." : null; }
public abstract WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList<ArraySegment<byte>> data);
// As server private void closeResourcesAsServer() { if (!_context.IsNull() && !_closeContext.IsNull()) { _closeContext(); _wsStream = null; _context = null; } }
private string checkHandshakeRequest(WebSocketContext context) { return _originValidator != null && !_originValidator (context.Origin) ? "Includes no Origin header, or it has an invalid value." : _cookiesValidator != null && !_cookiesValidator (context.CookieCollection, context.WebSocket.CookieCollection) ? "Includes no cookie, or an invalid cookie exists." : null; }
/// <summary> /// Starts a new session to the WebSocket service using the specified <see cref="WebSocketContext"/>. /// </summary> /// <param name="context"> /// A <see cref="WebSocketContext"/> that contains a WebSocket connection request objects. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="context"/> is <see langword="null"/>. /// </exception> internal void StartSession(WebSocketContext context) { if (context == null) throw new ArgumentNullException ("context"); var session = CreateSession (); session.Start (context, Sessions); }
public WebSocketMessageSource(WebSocketTransportDuplexSessionChannel webSocketTransportDuplexSessionChannel, WebSocketContext context, bool isStreamed, RemoteEndpointMessageProperty remoteEndpointMessageProperty, IDefaultCommunicationTimeouts defaultTimeouts, HttpContext requestContext) { Initialize(webSocketTransportDuplexSessionChannel, context.WebSocket, isStreamed, defaultTimeouts); IPrincipal user = requestContext?.User; _context = new ServiceWebSocketContext(context, user); RemoteEndpointMessageProperty = remoteEndpointMessageProperty; // Copy any string keyed items from requestContext to properties. This is an attempt to mimic HttpRequestMessage.Properties var properties = new Dictionary <string, object>(); foreach (KeyValuePair <object, object> kv in requestContext.Items) { if (kv.Key is string key) { properties[key] = kv.Value; } } _properties = requestContext == null ? null : new ReadOnlyDictionary <string, object>(properties); StartNextReceiveAsync(); }
// As server internal WebSocket(TcpListenerWebSocketContext context, string protocol, Logger logger) { _context = context; _protocol = protocol; _logger = logger; _closeContext = context.Close; _secure = context.IsSecureConnection; _stream = context.Stream; init (); }
/// <summary> /// Called when the server has removed a WebSockets connected client for any reason. /// </summary> /// <param name="context">The context.</param> protected override void OnClientDisconnected(WebSocketContext context) { this.Broadcast(string.Format("Someone left the chat room.")); }
internal void Start(WebSocketContext context, WebSocketSessionManager sessions) { _context = context; _sessions = sessions; _websocket = context.WebSocket; _websocket.Protocol = _protocol; _websocket.CookiesValidation = ValidateCookies; _websocket.OnOpen += onOpen; _websocket.OnMessage += onMessage; _websocket.OnError += onError; _websocket.OnClose += onClose; _websocket.ConnectAsServer (); }
public virtual bool OnValidateContext(WebSocketContext context, ref int errStatusCode, ref string statusDescription) { return(true); }
public BroadcastClientSubmitter(IWsSessionsManager wsSessionsManager, ISerializer serializer, WebSocketContext webSocketContext) : base(serializer, webSocketContext) { _wsSessionsManager = wsSessionsManager; }
// As server internal WebSocket(TcpListenerWebSocketContext context, Logger logger) { _context = context; _logger = logger; _closeContext = context.Close; _secure = context.IsSecureConnection; _stream = context.Stream; _uri = context.Path.ToUri (); init (); }
public EmbedIOSubscriptionApiConnection(BaseSubscriptionApi subscriptionApi, Action <string> send, WebSocketContext context) : base(subscriptionApi) { this.send = send; this.context = context; }
// As server private string checkIfValidHandshakeRequest (WebSocketContext context) { var headers = context.Headers; return context.RequestUri == null ? "Specifies an invalid Request-URI." : !context.IsWebSocketRequest ? "Not a WebSocket connection request." : !validateSecWebSocketKeyHeader (headers["Sec-WebSocket-Key"]) ? "Includes an invalid Sec-WebSocket-Key header." : !validateSecWebSocketVersionClientHeader (headers["Sec-WebSocket-Version"]) ? "Includes an invalid Sec-WebSocket-Version header." : CustomHandshakeRequestChecker (context); }
public EmbedIOWebSocketWebRequest(WebSocketContext context) { this.context = context; }
//### Accepting WebSocket connections // Calling `AcceptWebSocketAsync` on the `HttpListenerContext` will accept the WebSocket connection, sending the required 101 response to the client // and return an instance of `WebSocketContext`. This class captures relevant information available at the time of the request and is a read-only // type - you cannot perform any actual IO operations such as sending or receiving using the `WebSocketContext`. These operations can be // performed by accessing the `System.Net.WebSocket` instance via the `WebSocketContext.WebSocket` property. private async void ProcessRequest(HttpListenerContext listenerContext) { WebSocketContext webSocketContext = null; try { // When calling `AcceptWebSocketAsync` the negotiated subprotocol must be specified. This sample assumes that no subprotocol // was requested. webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol : null); Interlocked.Increment(ref count); Console.WriteLine("Processed: {0}", count); } catch (Exception e) { // The upgrade process failed somehow. For simplicity lets assume it was a failure on the part of the server and indicate this using 500. listenerContext.Response.StatusCode = 500; listenerContext.Response.Close(); Console.WriteLine("Exception: {0}", e); return; } WebSocket webSocket = webSocketContext.WebSocket; try { //### Receiving // Define a receive buffer to hold data received on the WebSocket connection. The buffer will be reused as we only need to hold on to the data // long enough to send it back to the sender. byte[] receiveBuffer = new byte[1024]; // While the WebSocket connection remains open run a simple loop that receives data and sends it back. while (webSocket.State == WebSocketState.Open) { // The first step is to begin a receive operation on the WebSocket. `ReceiveAsync` takes two parameters: // // * An `ArraySegment` to write the received data to. // * A cancellation token. In this example we are not using any timeouts so we use `CancellationToken.None`. // // `ReceiveAsync` returns a `Task<WebSocketReceiveResult>`. The `WebSocketReceiveResult` provides information on the receive operation that was just // completed, such as: // // * `WebSocketReceiveResult.MessageType` - What type of data was received and written to the provided buffer. Was it binary, utf8, or a close message? // * `WebSocketReceiveResult.Count` - How many bytes were read? // * `WebSocketReceiveResult.EndOfMessage` - Have we finished reading the data for this message or is there more coming? WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), CancellationToken.None); // The WebSocket protocol defines a close handshake that allows a party to send a close frame when they wish to gracefully shut down the connection. // The party on the other end can complete the close handshake by sending back a close frame. // // If we received a close frame then lets participate in the handshake by sending a close frame back. This is achieved by calling `CloseAsync`. // `CloseAsync` will also terminate the underlying TCP connection once the close handshake is complete. // // The WebSocket protocol defines different status codes that can be sent as part of a close frame and also allows a close message to be sent. // If we are just responding to the client's request to close we can just use `WebSocketCloseStatus.NormalClosure` and omit the close message. if (receiveResult.MessageType == WebSocketMessageType.Close) { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); } // This echo server can't handle text frames so if we receive any we close the connection with an appropriate status code and message. else if (receiveResult.MessageType == WebSocketMessageType.Text) { await webSocket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept text frame", CancellationToken.None); } // Otherwise we must have received binary data. Send it back by calling `SendAsync`. Note the use of the `EndOfMessage` flag on the receive result. This // means that if this echo server is sent one continuous stream of binary data (with EndOfMessage always false) it will just stream back the same thing. // If binary messages are received then the same binary messages are sent back. else { await webSocket.SendAsync(new ArraySegment <byte>(receiveBuffer, 0, receiveResult.Count), WebSocketMessageType.Binary, receiveResult.EndOfMessage, CancellationToken.None); } // The echo operation is complete. The loop will resume and `ReceiveAsync` is called again to wait for the next data frame. } } catch (Exception e) { // Just log any exceptions to the console. Pretty much any exception that occurs when calling `SendAsync`/`ReceiveAsync`/`CloseAsync` is unrecoverable in that it will abort the connection and leave the `WebSocket` instance in an unusable state. Console.WriteLine("Exception: {0}", e); } finally { // Clean up by disposing the WebSocket once it is closed/aborted. if (webSocket != null) { webSocket.Dispose(); } } }
protected override void OnClientDisconnected(WebSocketContext context) { this.channelByWebSocketContext.TryRemove(context, out EmbedIOSubscriptionApiConnection dummyContext); }
public void Handshake(WebSocketContext context) { Context = context; }
internal void StartSession (WebSocketContext context) { CreateSession ().Start (context, Sessions); }
private string checkIfValidConnectionRequest(WebSocketContext context) { return _originValidator != null && !_originValidator (context.Origin) ? "Invalid Origin header." : _cookiesValidator != null && !_cookiesValidator (context.CookieCollection, context.WebSocket.CookieCollection) ? "Invalid Cookies." : null; }
internal void StartSession(WebSocketContext context) { var session = CreateSession(); session.Start(context, Sessions); }
private string checkHandshakeRequest(WebSocketContext context) => ((this._originValidator == null) || this._originValidator(context.Origin)) ? (((this._cookiesValidator == null) || this._cookiesValidator(context.CookieCollection, context.WebSocket.CookieCollection)) ? null : "Includes no cookie, or an invalid cookie exists.") : "Includes no Origin header, or it has an invalid value.";
// As server private void closeResourcesAsServer() { if (_context != null && _closeContext != null) { _closeContext(); _wsStream = null; _context = null; } }
public abstract WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList <ArraySegment <byte> > data);
private static async Task WebSocketMessageReceived(WebSocketContext context, RTCPeerConnection pc, string message) { try { if (pc.localDescription == null) { //logger.LogDebug("Offer SDP: " + message); logger.LogDebug("Offer SDP received."); // Add local media tracks depending on what was offered. Also add local tracks with the same media ID as // the remote tracks so that the media announcement in the SDP answer are in the same order. SDP remoteSdp = SDP.ParseSDPDescription(message); foreach (var ann in remoteSdp.Media) { MediaStreamTrack track = new MediaStreamTrack(ann.Media, false, ann.MediaFormats.Values.ToList(), MediaStreamStatusEnum.RecvOnly); pc.addTrack(track); } pc.setRemoteDescription(new RTCSessionDescriptionInit { sdp = message, type = RTCSdpType.offer }); var answer = pc.createAnswer(null); await pc.setLocalDescription(answer); Console.WriteLine(answer.sdp); context.WebSocket.Send(answer.sdp); } else if (pc.remoteDescription == null) { logger.LogDebug("Answer SDP: " + message); var result = pc.setRemoteDescription(new RTCSessionDescriptionInit { sdp = message, type = RTCSdpType.answer }); if (result != SetDescriptionResultEnum.OK) { logger.LogWarning($"Failed to set remote description {result}."); } } else { logger.LogDebug("ICE Candidate: " + message); if (string.IsNullOrWhiteSpace(message) || message.Trim().ToLower() == SDP.END_ICE_CANDIDATES_ATTRIBUTE) { logger.LogDebug("End of candidates message received."); } else { var candInit = Newtonsoft.Json.JsonConvert.DeserializeObject <RTCIceCandidateInit>(message); pc.addIceCandidate(candInit); } } } catch (Exception excp) { logger.LogError("Exception WebSocketMessageReceived. " + excp.Message); } }
/// <summary> /// Called when this WebSockets Server receives a message frame regardless if the frame represents the EndOfMessage. /// </summary> /// <param name="context">The context.</param> /// <param name="rxBuffer">The rx buffer.</param> /// <param name="rxResult">The rx result.</param> protected override void OnFrameReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult) { // don't process partial frames return; }
// As server private bool checkHandshakeRequest (WebSocketContext context, out string message) { message = null; if (context.RequestUri == null) { message = "Specifies an invalid Request-URI."; return false; } if (!context.IsWebSocketRequest) { message = "Not a WebSocket handshake request."; return false; } var headers = context.Headers; if (!validateSecWebSocketKeyHeader (headers["Sec-WebSocket-Key"])) { message = "Includes no Sec-WebSocket-Key header, or it has an invalid value."; return false; } if (!validateSecWebSocketVersionClientHeader (headers["Sec-WebSocket-Version"])) { message = "Includes no Sec-WebSocket-Version header, or it has an invalid value."; return false; } return true; }
/// <summary> /// Called when this WebSockets Server receives a message frame regardless if the frame represents the EndOfMessage. /// </summary> /// <param name="context">The context.</param> /// <param name="rxBuffer">The rx buffer.</param> /// <param name="rxResult">The rx result.</param> protected override void OnFrameReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult) { return; }
// As server private bool customCheckHandshakeRequest (WebSocketContext context, out string message) { message = null; return _handshakeRequestChecker == null || (message = _handshakeRequestChecker (context)) == null; }
internal void StartSession(WebSocketContext context) { CreateSession().Start(context, _sessions); }
public async void Execute(HttpListenerContext listenerContext) { _exception = null; //int count = 0; _remoteAddress = listenerContext.Request.RemoteEndPoint.ToString(); WebSocketContext webSocketContext = null; try { // When calling `AcceptWebSocketAsync` the negotiated subprotocol must be specified. This sample assumes that no subprotocol // was requested. webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol : null); //Interlocked.Increment(ref count); } catch (Exception e) { _exception = e; listenerContext.Response.StatusCode = 500; listenerContext.Response.Close(); return; } WebSocket webSocket = webSocketContext.WebSocket; if (webSocket.State != WebSocketState.Open) { } try { byte[] buffer = new byte[1024]; while (_exception == null && webSocket.State == WebSocketState.Open) { WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); if ((_hpsmUser.Command == WSClientStatus.closed || _hpsmUser.Command == WSClientStatus.unreg)) { break; } if (receiveResult.MessageType == WebSocketMessageType.Close) { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); } else if (receiveResult.MessageType == WebSocketMessageType.Text) { string command = Encoding.UTF8.GetString(buffer, 0, receiveResult.Count); _response_on_command(webSocket, command); // await webSocket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept text frame", CancellationToken.None); } else //binary data { await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, receiveResult.Count), WebSocketMessageType.Binary, receiveResult.EndOfMessage, CancellationToken.None); } //if(_exception != null) //{ // break; //} }//end if client loop } catch (ApplicationException e) { _exception = e; } catch (Exception e) { _exception = e; } finally { _unregister_marabu_user(); } //if (webSocket != null) //{ // webSocket = null; //} }
public virtual string GetClientId(WebSocketContext ctx) { return(Guid.NewGuid().ToString()); }
private async Task ProcessRequest <TWebSocketBehavior>(HttpListenerContext listenerContext, Func <TWebSocketBehavior> behaviorBuilder) where TWebSocketBehavior : WebSocketServerBehavior { WebSocketContext webSocketContext = null; WebSocketServerBehavior behavior = null; string clientId; try { webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol : null); behavior = behaviorBuilder(); int statusCode = 500; var statusDescription = "BadContext"; if (!behavior.OnValidateContext(webSocketContext, ref statusCode, ref statusDescription)) { listenerContext.Response.StatusDescription = statusDescription; listenerContext.Response.StatusCode = statusCode; listenerContext.Response.Close(); return; } clientId = behavior.GetClientId(webSocketContext); _clients.TryAdd(clientId, webSocketContext); Interlocked.Increment(ref count); _logInfo($"Client id:{clientId} accepted now there are {count} clients"); behavior.OnClientConnected(clientId); } catch (Exception e) { listenerContext.Response.StatusCode = 500; listenerContext.Response.Close(); this._logError($"Exception: {e}"); return; } try { await RecieveLoop(webSocketContext.WebSocket, behavior.OnBinaryMessage, behavior.OnStringMessage, (e) => { Interlocked.Decrement(ref count); this._logInfo($"Client disconnected. now {count} connected clients"); behavior.OnClose(new WebSocketClosedEventArgs(clientId, e.ReceivedResult)); }); } finally { if (webSocketContext.WebSocket != null) { webSocketContext.WebSocket.Dispose(); } // _cleanup(); if (!string.IsNullOrEmpty(clientId)) { _clients.TryRemove(clientId, out webSocketContext); } } }
public virtual Task ExecuteResultAsync(WebSocketContext context) { ExecuteResult(context); return(TaskCache.CompletedTask); }
/// <summary> /// Called when this WebSockets Server receives a message frame regardless if the frame represents the EndOfMessage. /// </summary> /// <param name="context">The context.</param> /// <param name="rxBuffer">The response buffer.</param> /// <param name="rxResult">The response result.</param> protected abstract void OnFrameReceived( WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult);
// As server private string checkIfValidHandshakeRequest(WebSocketContext context) { var headers = context.Headers; return !context.IsWebSocketRequest ? "Not WebSocket connection request." : !validateHostHeader (headers ["Host"]) ? "Invalid Host header." : !validateSecWebSocketKeyHeader (headers ["Sec-WebSocket-Key"]) ? "Invalid Sec-WebSocket-Key header." : !validateSecWebSocketVersionClientHeader (headers ["Sec-WebSocket-Version"]) ? "Invalid Sec-WebSocket-Version header." : CustomHandshakeRequestChecker (context); }
/// <summary> /// Called when the server has removed a WebSockets connected client for any reason. /// </summary> /// <param name="context">The context.</param> protected abstract void OnClientDisconnected(WebSocketContext context);
private async void ProcessRequests(HttpListenerContext context) { try { WebSocketContext webSocketContext = await context.AcceptWebSocketAsync(subProtocol : null); PrintKeysAndValues(webSocketContext.Headers); string ipAddres = context.Request.RemoteEndPoint.Address.ToString(); Console.WriteLine($"Got WebSocket connection from {ipAddres}"); WebSocket socket = webSocketContext.WebSocket; Console.WriteLine($"SubProtocol={socket.SubProtocol}"); var receive = Receive(socket); await Task.Delay(1000); var settings = new JsonSerializerSettings(); settings.NullValueHandling = NullValueHandling.Ignore; settings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate; settings.MissingMemberHandling = MissingMemberHandling.Error; settings.Formatting = Formatting.Indented; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); var message = new Message() { Header = new MessageHeader() { //RequestId = "External", //RequestId = "3", //RequestId = "automation", RequestId = Guid.NewGuid().ToString(), Version = 1, MessagePurpose = "subscribe", //MessagePurpose = "commandRequest" MessageType = "commandRequest" }, //Body = "/kill @e" Body = new MessageBody() { Origin = "External", //CommandName = "helpasdf", //Command = "helpasdf", EventName = "BlockPlaced", //Body = "" } }; string content = JsonConvert.SerializeObject(message, settings); //string content = "{\"body\":{\"input\":{\"dimension\":\"overworld\",\"chunkX\":13,\"chunkZ\":4,\"height\":128},\"origin\":{\"type\":\"player\"},\"name\":\"getchunkdata\",\"version\":1,\"overload\":\"default\"},\"header\":{\"requestId\":\"c8c4d791-1e88-49a4-bbef-204c5462982d\",\"messagePurpose\":\"commandRequest\",\"version\":1,\"messageType\":\"commandRequest\"}}"; Console.WriteLine(content); byte[] buffer = Encoding.UTF8.GetBytes(content); Console.WriteLine($"Sending content"); await socket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None); await receive; } catch (Exception e) { Console.WriteLine(e); } }
private async Task AcceptConnections() { try { _Listener.Start(); while (true) { if (_Token.IsCancellationRequested) { break; } if (!_Listener.IsListening) { Task.Delay(100).Wait(); continue; } HttpListenerContext ctx = await _Listener.GetContextAsync(); string ip = ctx.Request.RemoteEndPoint.Address.ToString(); int port = ctx.Request.RemoteEndPoint.Port; string ipPort = ip + ":" + port; lock (_PermittedIpsLock) { if (PermittedIpAddresses != null && PermittedIpAddresses.Count > 0 && !PermittedIpAddresses.Contains(ip)) { Logger?.Invoke(_Header + "rejecting " + ipPort + " (not permitted)"); ctx.Response.StatusCode = 401; ctx.Response.Close(); continue; } } if (!ctx.Request.IsWebSocketRequest) { if (HttpHandler == null) { Logger?.Invoke(_Header + "non-websocket request rejected from " + ipPort); ctx.Response.StatusCode = 400; ctx.Response.Close(); } else { Logger?.Invoke(_Header + "non-websocket request from " + ipPort + " HTTP-forwarded: " + ctx.Request.HttpMethod.ToString() + " " + ctx.Request.RawUrl); HttpHandler.Invoke(ctx); } continue; } else { /* * HttpListenerRequest req = ctx.Request; * Console.WriteLine(Environment.NewLine + req.HttpMethod.ToString() + " " + req.RawUrl); * if (req.Headers != null && req.Headers.Count > 0) * { * Console.WriteLine("Headers:"); * var items = req.Headers.AllKeys.SelectMany(req.Headers.GetValues, (k, v) => new { key = k, value = v }); * foreach (var item in items) * { * Console.WriteLine(" {0}: {1}", item.key, item.value); * } * } */ } await Task.Run(() => { Logger?.Invoke(_Header + "starting data receiver for " + ipPort); CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; Task.Run(async() => { WebSocketContext wsContext = await ctx.AcceptWebSocketAsync(subProtocol: null); WebSocket ws = wsContext.WebSocket; ClientMetadata md = new ClientMetadata(ctx, ws, wsContext, tokenSource); _Clients.TryAdd(md.IpPort, md); ClientConnected?.Invoke(this, new ClientConnectedEventArgs(md.IpPort, ctx.Request)); await Task.Run(() => DataReceiver(md), token); }, token); }, _Token); } } catch (HttpListenerException) { // thrown when disposed } catch (OperationCanceledException) { // thrown when disposed } catch (ObjectDisposedException) { // thrown when disposed } catch (Exception e) { Logger?.Invoke(_Header + "listener exception:" + Environment.NewLine + e.ToString()); } finally { ServerStopped?.Invoke(this, EventArgs.Empty); } }
// As server internal WebSocket (TcpListenerWebSocketContext context, string protocol) { _context = context; _protocol = protocol; _closeContext = context.Close; _logger = context.Log; _secure = context.IsSecureConnection; _stream = context.Stream; _waitTime = TimeSpan.FromSeconds (1); init (); }
// As server private void closeServerResources() { if (_closeContext != null) _closeContext (); _stream = null; _context = null; }
// As server private bool closeServerResources() { try { if (_closeContext != null) _closeContext (); _stream = null; _context = null; return true; } catch (Exception ex) { _logger.Fatal (ex.ToString ()); error ("An exception has occurred."); return false; } }
protected override void OnMessageReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult) { }
// As server private bool validateConnectionRequest(WebSocketContext context) { string version; return context.IsWebSocketRequest && validateHostHeader (context.Host) && !context.SecWebSocketKey.IsNullOrEmpty () && ((version = context.SecWebSocketVersion) != null && version == _version) && validateCookies (context.CookieCollection, _cookies); }
protected override void OnClientDisconnected(WebSocketContext context) { _connected--; }
private async static void ProcessWebSocketRequest(HttpListenerContext context) { WebSocketContext wsContext = null; try { wsContext = await context.AcceptWebSocketAsync(SFXProtocol); } catch (Exception e) { context.Response.StatusCode = 500; context.Response.Close(); Debug.WriteLine("Exception: {0}", e); return; } WebSocket ws = wsContext.WebSocket; if (LastMessage != null) { await ws.SendAsync(new ArraySegment <byte>(LastMessage, 0, LastMessage.Length), WebSocketMessageType.Text, true, CancellationToken.None); } lock (webSockets) { webSockets.Add(ws); } try { byte[] receiveBuffer = new byte[1024]; while (ws.State == WebSocketState.Open) { WebSocketReceiveResult receiveResult = await ws.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), CancellationToken.None); if (receiveResult.MessageType == WebSocketMessageType.Close) { lock (webSockets) { webSockets.Remove(ws); } await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close requested by remote", CancellationToken.None); } else { //TODO: code for received messages goes here! string strXML = Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count); //Debug.WriteLine(strXML); XmlDocument xml = new XmlDocument(); xml.LoadXml(strXML); var nodes = xml.SelectNodes("command"); foreach (XmlNode childrenNode in nodes) { //Debug.WriteLine(childrenNode.Name); //Debug.WriteLine(childrenNode.InnerText); string command = childrenNode.InnerText.ToLower(); switch (command) { case "play": Program.mainForm.PlayNextCue(); break; case "stop": Program.mainForm.StopAll(); break; case "previous": Program.mainForm.PreviousCue(); break; case "next": Program.mainForm.NextCue(); break; } } } } } catch (Exception e) { Debug.WriteLine("Exception: {0}", e); } finally { if (ws != null) { lock (webSockets) { webSockets.Remove(ws); } ws.Dispose(); } } }
public override WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList<ArraySegment<byte>> data) { throw new NotImplementedException(); }