コード例 #1
0
        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);
        }
コード例 #2
0
        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);
        }
コード例 #3
0
 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
ファイル: WebSocketsSample.cs プロジェクト: ngdadu/embedio
 /// <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
ファイル: WebSocketsSample.cs プロジェクト: ngdadu/embedio
 /// <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
ファイル: WebSocketHandler.cs プロジェクト: jn2304/top-push
        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);
                }
            }
        }
コード例 #7
0
        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
ファイル: MatchSocket.cs プロジェクト: Gomocup/GomocupOnline
        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);
                }
            }
        }
コード例 #10
0
        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
ファイル: WebSocketsSample.cs プロジェクト: ngdadu/embedio
 /// <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
ファイル: WebSocketsSample.cs プロジェクト: ngdadu/embedio
 /// <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
ファイル: WebSocketsSample.cs プロジェクト: ngdadu/embedio
 /// <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();
     }
 }
コード例 #14
0
		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
ファイル: LocalSessionModule.cs プロジェクト: ngdadu/embedio
        /// <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
ファイル: WebSocketsSample.cs プロジェクト: ngdadu/embedio
 /// <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
ファイル: Extensions.cs プロジェクト: purgatorium/embedio
        /// <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
ファイル: WebSocketsSample.cs プロジェクト: ngdadu/embedio
 /// <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."));
 }
コード例 #25
0
 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);
     }
 }
コード例 #27
0
            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
ファイル: WebSocketsSample.cs プロジェクト: ngdadu/embedio
        /// <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();
        }
コード例 #30
0
 protected abstract void OnAcceptWebSocketSuccess(WebSocketContext context, HttpRequestMessage requestMessage);
コード例 #31
0
 public ServiceWebSocketContext(WebSocketContext context, IPrincipal user)
 {
     Fx.Assert(context != null, "context should not be null.");
     this.context = context;
     this.user = user;
 }