protected override async Task HandleWebSocket(WebSocketContext context, bool closeConnection = true)
        {
            if (context == null)
                throw new ApplicationException("Could not determine websocket context.");

            BlockingStream stream = new BlockingStream(16);

            var ws = context.WebSocket;

            var send = Task.Factory.StartNew(async () =>
            {
                int read = 0;
                byte[] readBuffer = new byte[1024 * 63];
                //max tcp packet size is 64K, but there is control data included, leave some bytes for that
                while ((read = stream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                {
                    byte[] sendBuffer = readBuffer;
                    if (read < readBuffer.Length)
                    {
                        sendBuffer = new byte[read];
                        Buffer.BlockCopy(readBuffer, 0, sendBuffer, 0, read);
                    }

                    await
                        ws.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true,
                            CancellationToken.None);
                }
                await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            });

            StreamHandlerAction(stream);
            stream.CompleteWriting();

            Task.WaitAll(send);
        }
        protected override async Task HandleWebSocket(WebSocketContext context, bool closeConnection = true)
        {
            if (context == null)
                throw new ApplicationException("Could not determine websocket context.");

            BlockingStream stream = new BlockingStream(16);

            var ws = context.WebSocket;

            new Task(async () =>
            {
                byte[] buffer = new byte[1024 * 64];

                while (true)
                {
                    // MUST read if we want the state to get updated...
                    var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                    stream.Write(buffer, 0, result.Count);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        if (closeConnection)
                            await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, CancellationToken.None);
                        stream.CompleteWriting();
                        break;
                    }
                }
            }).Start();

            StreamHandlerAction(stream);
        }
 internal WebSocketMessageProperty(WebSocketContext context, string subProtocol, WebSocketMessageType incomingMessageType, ReadOnlyDictionary<string, object> properties)
 {
     this.context = context;
     this.subProtocol = subProtocol;
     this.messageType = incomingMessageType;
     this.properties = properties;
 }
示例#4
0
 /// <summary>
 /// Called when this WebSockets Server accepts a new WebSockets client.
 /// </summary>
 /// <param name="context">The context.</param>
 protected override void OnClientConnected(WebSocketContext context)
 {
     this.Send(context, "Welcome to the chat room!");
     foreach (var ws in this.WebSockets)
     {
         if (ws != context)
             this.Send(ws, "Someone joined the chat room.");
     }
 }
示例#5
0
 /// <summary>
 /// Called when this WebSockets Server receives a full message (EndOfMessage) form a WebSockets client.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="rxBuffer">The rx buffer.</param>
 /// <param name="rxResult">The rx result.</param>
 protected override void OnMessageReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult)
 {
     var session = this.WebServer.GetSession(context);
     foreach (var ws in this.WebSockets)
     {
         if (ws != context)
             this.Send(ws, Encoding.UTF8.GetString(rxBuffer));
     }
 }
示例#6
0
        private async Task HandleWebSocket(WebSocketContext context)
        {
            var maxMessageSize = 1024;
            var receiveBuffer = new byte[maxMessageSize];
            var socket = context.WebSocket;

            var total = 0;
            
            while (socket.State == WebSocketState.Open)
            {
                var ret = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);

                if (ret.MessageType == WebSocketMessageType.Close)              
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure
                        , string.Empty
                        , CancellationToken.None);
                else if (ret.MessageType == WebSocketMessageType.Binary)
                    await socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType
                        , "Cannot accept binary frame"
                        , CancellationToken.None);
                else
                {
                    var count = ret.Count;
                    while (!ret.EndOfMessage)
                    {
                        if (count >= maxMessageSize)
                        {
                            await socket.CloseAsync(WebSocketCloseStatus.MessageTooBig
                                , string.Format("Maximum message size: {0} bytes.", maxMessageSize)
                                , CancellationToken.None);
                            return;
                        }

                        ret = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer, count, maxMessageSize - count), CancellationToken.None);
                        count += ret.Count;
                    }

                    var receivedString = Encoding.UTF8.GetString(receiveBuffer, 0, count);

                    if (total == 0)
                    {
                        total = int.Parse(receivedString);
                        continue;
                    }

                    var outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(receivedString));
                    var w = new Stopwatch();
                    w.Start();
                    for (var i = 0; i < total; i++)
                        await socket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
                    w.Stop();
                    Console.WriteLine(w.ElapsedMilliseconds);
                }
            }
        }
        internal OwinWebSocketWrapper(WebSocketContext context, CancellationToken ct)
        {
            _context = context;
            _webSocket = _context.WebSocket;
            _cancellationToken = ct;

            _environment = new Dictionary<string, object>();
            _environment[Constants.WebSocketSendAsyncKey] = new WebSocketSendAsync(SendAsync);
            _environment[Constants.WebSocketReceiveAyncKey] = new WebSocketReceiveAsync(ReceiveAsync);
            _environment[Constants.WebSocketCloseAsyncKey] = new WebSocketCloseAsync(CloseAsync);
            _environment[Constants.WebSocketCallCancelledKey] = ct;
            _environment[Constants.WebSocketVersionKey] = Constants.WebSocketVersion;

            _environment[typeof(WebSocketContext).FullName] = _context;
        }
示例#8
0
        internal OwinWebSocketWrapper(WebSocketContext context)
        {
            Contract.Assert(context != null);
            _trace = TraceFactory.Create(TraceName);
            _context = context;
            _cancellationTokenSource = new CancellationTokenSource();

            _environment = new ConcurrentDictionary<string, object>();
            _environment[WebSocketConstants.WebSocketSendAsyncKey] = new WebSocketSendAsync(SendAsync);
            _environment[WebSocketConstants.WebSocketReceiveAyncKey] = new WebSocketReceiveAsync(ReceiveAsync);
            _environment[WebSocketConstants.WebSocketCloseAsyncKey] = new WebSocketCloseAsync(CloseAsync);
            _environment[WebSocketConstants.WebSocketCallCancelledKey] = _cancellationTokenSource.Token;
            _environment[WebSocketConstants.WebSocketVersionKey] = WebSocketConstants.WebSocketVersion;

            _environment[typeof(WebSocketContext).FullName] = _context;
        }
示例#9
0
        private async Task HandleWebSocket(WebSocketContext wsContext)
        {
            const int maxMessageSize = 1024;
            byte[] receiveBuffer = new byte[maxMessageSize];
            WebSocket socket = wsContext.WebSocket;

            while (socket.State == WebSocketState.Open)
            {
                WebSocketReceiveResult receiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                if (receiveResult.MessageType == WebSocketMessageType.Close)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }
                else if (receiveResult.MessageType == WebSocketMessageType.Binary)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame", CancellationToken.None);
                }
                else
                {
                    int count = receiveResult.Count;

                    while (receiveResult.EndOfMessage == false)
                    {
                        if (count >= maxMessageSize)
                        {
                            string closeMessage = string.Format("Maximum message size: {0} bytes.", maxMessageSize);
                            await socket.CloseAsync(WebSocketCloseStatus.MessageTooBig, closeMessage, CancellationToken.None);
                            return;
                        }
                        receiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer, count, maxMessageSize - count), CancellationToken.None);
                        count += receiveResult.Count;
                    }
                    var receivedString = Encoding.UTF8.GetString(receiveBuffer, 0, count);


                    var echoString = "You said " + receivedString;
                    ArraySegment<byte> outputBuffer = new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes(echoString));

                    await socket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
                }
            }
        }
        private async Task ProcessWebSocketRequest(WebSocketContext wsContext)
        {
            WebSocket socket = wsContext.WebSocket;
            var receiveBuffer = new byte[MaxBufferSize];

            // Reflect all headers and cookies
            var sb = new StringBuilder();
            sb.AppendLine("Headers:");

            foreach (string header in wsContext.Headers.AllKeys)
            {
                sb.Append(header);
                sb.Append(":");
                sb.AppendLine(wsContext.Headers[header]);
            }

            byte[] sendBuffer = Encoding.UTF8.GetBytes(sb.ToString());
            await socket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Text, true, new CancellationToken());

            // Stay in loop while websocket is open
            while (socket.State == WebSocketState.Open || socket.State == WebSocketState.CloseSent)
            {
                var receiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                if (receiveResult.MessageType == WebSocketMessageType.Close)
                {
                    if (receiveResult.CloseStatus == WebSocketCloseStatus.Empty)
                    {
                        await socket.CloseAsync(WebSocketCloseStatus.Empty, null, CancellationToken.None);
                    }
                    else
                    {
                        await socket.CloseAsync(
                            receiveResult.CloseStatus.GetValueOrDefault(),
                            receiveResult.CloseStatusDescription,
                            CancellationToken.None);
                    }

                    continue;
                }
            }
        }
示例#11
0
 /// <summary>
 /// Called when this WebSockets Server receives a full message (EndOfMessage) form a WebSockets client.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="rxBuffer">The rx buffer.</param>
 /// <param name="rxResult">The rx result.</param>
 protected override void OnMessageReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult)
 {
     lock (SyncRoot)
     {
         var arg = System.Text.Encoding.UTF8.GetString(rxBuffer);
         Processes[context].StandardInput.WriteLine(arg);
     }
 }
示例#12
0
 /// <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;
 }
示例#13
0
 /// <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)
 {
     lock (SyncRoot)
     {
         if (Processes[context].HasExited == false)
             Processes[context].Kill();
     }
 }
		private void ContinuationAction(Task<HttpListenerWebSocketContext> task)
		{
			_webSocketContext = task.Result;
			_webSocket = _webSocketContext.WebSocket;
			//if(_webSocket.State == WebSocketState.)
		}
示例#15
0
文件: Network.cs 项目: oojjrs/Nuri4
 private void OnAccept(WebSocketContext context)
 {
     Contexts.Add(context);
 }
示例#16
0
        /// <summary>
        /// Gets the session.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public SessionInfo GetSession(WebSocketContext context)
        {
            if (context.CookieCollection[SessionCookieName] == null ||
                Sessions.ContainsKey(context.CookieCollection[SessionCookieName].Value) == false)
                return null;

            return Sessions[context.CookieCollection[SessionCookieName].Value];
        }
示例#17
0
 /// <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;
 }
示例#18
0
 protected override void OnMessageReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult) {}
示例#19
0
        /// <summary>
        /// Gets the session.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="context">The context.</param>
        /// <returns>A session info for the given websocket context</returns>
#if NET47
        public static SessionInfo GetSession(this WebServer server, System.Net.WebSockets.WebSocketContext context)
示例#20
0
 protected abstract Task HandleWebSocket(WebSocketContext context, bool closeConnection = true);
示例#21
0
 public async Task ProcessAspWebSocketSession(WebSocketContext context)
 {
     await HandleWebSocket(context);
 }
示例#22
0
        private async Task ProcessWebSocketRequest(WebSocketContext wsContext)
        {
            WebSocket socket = wsContext.WebSocket;
            var receiveBuffer = new byte[MaxBufferSize];
            var throwAwayBuffer = new byte[MaxBufferSize];

            // Stay in loop while websocket is open
            while (socket.State == WebSocketState.Open || socket.State == WebSocketState.CloseSent)
            {
                var receiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                if (receiveResult.MessageType == WebSocketMessageType.Close)
                {
                    if (receiveResult.CloseStatus == WebSocketCloseStatus.Empty)
                    {
                        await socket.CloseAsync(WebSocketCloseStatus.Empty, null, CancellationToken.None);
                    }
                    else
                    {
                        await socket.CloseAsync(
                            receiveResult.CloseStatus.GetValueOrDefault(),
                            receiveResult.CloseStatusDescription,
                            CancellationToken.None);
                    }

                    continue;
                }

                // Keep reading until we get an entire message.
                int offset = receiveResult.Count;
                while (receiveResult.EndOfMessage == false)
                {
                    if (offset < MaxBufferSize)
                    {
                        receiveResult = await socket.ReceiveAsync(
                            new ArraySegment<byte>(receiveBuffer, offset, MaxBufferSize - offset),
                            CancellationToken.None);
                    }
                    else
                    {
                        receiveResult = await socket.ReceiveAsync(
                            new ArraySegment<byte>(throwAwayBuffer),
                            CancellationToken.None);
                    }

                    offset += receiveResult.Count;
                }

                // Close socket if the message was too big.
                if (offset > MaxBufferSize)
                {
                    await socket.CloseAsync(
                        WebSocketCloseStatus.MessageTooBig,
                        String.Format("{0}: {1} > {2}", WebSocketCloseStatus.MessageTooBig.ToString(), offset, MaxBufferSize),
                        CancellationToken.None);

                    continue;
                }

                bool sendMessage = false;
                if (receiveResult.MessageType == WebSocketMessageType.Text)
                {
                    string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, offset);
                    if (receivedMessage == ".close")
                    {
                        await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, receivedMessage, CancellationToken.None);
                    }
                    if (receivedMessage == ".shutdown")
                    {
                        await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, receivedMessage, CancellationToken.None);
                    }
                    else if (receivedMessage == ".abort")
                    {
                        socket.Abort();
                    }
                    else if (receivedMessage == ".delay5sec")
                    {
                        await Task.Delay(5000);
                    }
                    else if (socket.State == WebSocketState.Open)
                    {
                        sendMessage = true;
                    }
                }
                else
                {
                    sendMessage = true;
                }

                if (sendMessage)
                {
                    await socket.SendAsync(
                            new ArraySegment<byte>(receiveBuffer, 0, offset),
                            receiveResult.MessageType,
                            true,
                            CancellationToken.None);
                }
            }
        }
示例#23
0
 protected override void OnClientDisconnected(WebSocketContext context) {}
示例#24
0
 /// <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."));
 }
 protected void OnAcceptWebSocketSuccess(
     WebSocketContext context, 
     RemoteEndpointMessageProperty remoteEndpointMessageProperty, 
     byte[] webSocketInternalBuffer, 
     bool shouldDisposeWebSocketAfterClose, 
     HttpRequestMessage requestMessage)
 {
     this.webSocketChannel.SetWebSocketInfo(
         context, 
         remoteEndpointMessageProperty, 
         this.securityProperty, 
         webSocketInternalBuffer,
         shouldDisposeWebSocketAfterClose, 
         requestMessage);
 }
示例#26
0
 protected override void OnClientConnected(WebSocketContext context) {
     if (_data != null) {
         Send(context, _data);
     }
 }
            protected override void OnAcceptWebSocketSuccess(WebSocketContext context, HttpRequestMessage requestMessage)
            {
                RemoteEndpointMessageProperty remoteEndpointMessageProperty = null;
                if (this.listenerContext.Request.RemoteEndPoint != null)
                {
                    remoteEndpointMessageProperty = new RemoteEndpointMessageProperty(this.listenerContext.Request.RemoteEndPoint);
                }

                base.OnAcceptWebSocketSuccess(context, remoteEndpointMessageProperty, this.webSocketInternalBuffer, true, requestMessage);
            }
示例#28
0
 protected override void OnAcceptWebSocketSuccess(WebSocketContext context, HttpRequestMessage requestMessage)
 {
     // ASP.NET owns the WebSocket object and needs it during the cleanup process. We should not dispose the WebSocket in WCF layer.
     base.OnAcceptWebSocketSuccess(context, this.remoteEndpointMessageProperty, null, false, requestMessage);
 }
示例#29
0
        /// <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();
        }
 protected abstract void OnAcceptWebSocketSuccess(WebSocketContext context, HttpRequestMessage requestMessage);
 public ServiceWebSocketContext(WebSocketContext context, IPrincipal user)
 {
     Fx.Assert(context != null, "context should not be null.");
     this.context = context;
     this.user = user;
 }