ReceiveAsync() public abstract method

public abstract ReceiveAsync ( System buffer, System cancellationToken ) : System.Threading.Tasks.Task
buffer System
cancellationToken System
return System.Threading.Tasks.Task
Beispiel #1
0
        private async Task HandleSocket(WebSocket socket)
        {
            var receiveBuffer = new byte[1024 * 4];
            try
            {
                var result = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                while (!socket.CloseStatus.HasValue)
                {
                    await Task.WhenAll(tasks: SocketsSingleton.Instance.SocketsBag.Where(x => x.State == WebSocketState.Open)
                        .Select(async x =>
                        {
                            await x.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
                        }));

                    SocketsSingleton.Instance.SocketsBag = new ConcurrentBag<WebSocket>(SocketsSingleton.Instance.SocketsBag.Where(x => x.State == WebSocketState.Open));
                    result = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                }
                await socket.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.EndpointUnavailable, result.CloseStatusDescription, CancellationToken.None);
            }
            catch (Exception exception)
            {
                Console.Write(exception);
            }
            finally
            {
                socket?.Dispose();
            }
        }
        public static async Task<WebSocketMessage> ReadMessageAsync(WebSocket webSocket, byte[] buffer, int maxMessageSize)
        {
            ArraySegment<byte> arraySegment = new ArraySegment<byte>(buffer);

            WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false);
            // special-case close messages since they might not have the EOF flag set
            if (receiveResult.MessageType == WebSocketMessageType.Close)
            {
                return new WebSocketMessage(null, WebSocketMessageType.Close);
            }

            if (receiveResult.EndOfMessage)
            {
                // we anticipate that single-fragment messages will be common, so we optimize for them
                switch (receiveResult.MessageType)
                {
                    case WebSocketMessageType.Binary:
                        return new WebSocketMessage(BufferSliceToByteArray(buffer, receiveResult.Count), WebSocketMessageType.Binary);

                    case WebSocketMessageType.Text:
                        return new WebSocketMessage(BufferSliceToString(buffer, receiveResult.Count), WebSocketMessageType.Text);

                    default:
                        throw new Exception("This code path should never be hit.");
                }
            }
            else
            {
                // for multi-fragment messages, we need to coalesce
                ByteBuffer bytebuffer = new ByteBuffer(maxMessageSize);
                bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                WebSocketMessageType originalMessageType = receiveResult.MessageType;

                while (true)
                {
                    // loop until an error occurs or we see EOF
                    receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false);
                    if (receiveResult.MessageType != originalMessageType)
                    {
                        throw new InvalidOperationException("Incorrect message type");
                    }

                    bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                    if (receiveResult.EndOfMessage)
                    {
                        switch (receiveResult.MessageType)
                        {
                            case WebSocketMessageType.Binary:
                                return new WebSocketMessage(bytebuffer.GetByteArray(), WebSocketMessageType.Binary);

                            case WebSocketMessageType.Text:
                                return new WebSocketMessage(bytebuffer.GetString(), WebSocketMessageType.Text);

                            default:
                                throw new Exception("This code path should never be hit.");
                        }
                    }
                }
            }
        }
Beispiel #3
0
        public async Task ProcessWebSocket(HttpContext context, WebSocket webSocket)
        {
            var connection = new Connection(context, webSocket);
            Console.WriteLine("Connect: {0}", context.Connection.RemoteIpAddress);

            var cancelToken = CancellationToken.None;
            var buffer = new byte[1024];
            WebSocketReceiveResult received =
                await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);

            while (!webSocket.CloseStatus.HasValue)
            {
                string text = System.Text.Encoding.UTF8.GetString(buffer, 0, received.Count);

                Console.WriteLine("Recd: {0}", text);

                try
                {
                    Cmd.Parse(text, connection)?.Run();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unhandled exception: {0}", ex);
                }

                received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);
            }

            await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, cancelToken);
        }
        public static async Task ExecuteAPI(HttpContext context, System.Net.WebSockets.WebSocket webSocket)
        {
            var buffer = new byte[1024 * 20];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                string strRequest = Encoding.UTF8.GetString(buffer);
                string str        = strRequest.Replace("\0", string.Empty);
                string jsonStr    = string.Empty;

                try
                {
                    //Method
                    APIModel    apiModel = JsonSerializer.Deserialize <APIModel>(str);
                    string      apiName  = apiModel.Method;
                    BaseCommand command  = Activator.CreateInstance(CommandsDict[apiName]) as BaseCommand;
                    command.WebSocket = webSocket;
                    jsonStr           = command.Execute(str);
                    buffer            = Encoding.UTF8.GetBytes(jsonStr);
                    BaseRequestModel requestModel = JsonSerializer.Deserialize <BaseRequestModel>(str);
                    if (!string.IsNullOrEmpty(requestModel.Token))
                    {
                        if (command is UserLogoutCommand)
                        {
                            //do nothing
                        }
                        else
                        {
                            UserInfo userInfo = UserInfoDict[requestModel.Token];
                            userInfo.ActionTime = DateTime.Now;
                        }
                    }
                    else if (command is UserLoginCommand)
                    {
                        //do nothing
                    }
                }
                catch (Exception ex)
                {
                    ErrorResponseModel responseModel = new ErrorResponseModel();
                    responseModel.StatusCode = 0;
                    responseModel.ErrorCode  = "500";
                    responseModel.Message    = ex.Message;
                    jsonStr = JsonSerializer.Serialize(responseModel);
                    buffer  = Encoding.UTF8.GetBytes(jsonStr);
                }

                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, jsonStr.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);

                buffer = new byte[1024 * 20];
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
Beispiel #5
0
 private async Task Echo(WebSocket webSocket)
 {
     byte[] buffer = new byte[1024 * 4];
     var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
     while (!result.CloseStatus.HasValue)
     {
         await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
         result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
     }
     await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
 }
        private static async Task Echo(HttpContext context, System.Net.WebSockets.WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
Beispiel #7
0
        private async Task EchoWebSocket(WebSocket webSocket)
        {
            byte[] buffer = new byte[1024];
            WebSocketReceiveResult received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

            while (!webSocket.CloseStatus.HasValue)
            {
                // Echo anything we receive
                await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, received.Count), received.MessageType, received.EndOfMessage, CancellationToken.None);

                received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }

            await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, CancellationToken.None);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="webSocket"></param>
        /// <returns></returns>
        public async Task ConnectClientAsync(System.Net.WebSockets.WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                string content = Encoding.UTF8.GetString(buffer);

                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }

            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
        private static async Task Receive(System.Net.WebSockets.WebSocket socket,
                                          Action <WebSocketReceiveResult, string> handleMessage)
        {
            while (socket.State == WebSocketState.Open)
            {
                var    buffer = new ArraySegment <byte>(new byte[1024 * 4]);
                string message;
                WebSocketReceiveResult result;
                using (var ms = new MemoryStream())
                {
                    do
                    {
                        result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                        ms.Write(buffer.Array, buffer.Offset, result.Count);
                    } while (!result.EndOfMessage);

                    ms.Seek(0, SeekOrigin.Begin);

                    using (var reader = new StreamReader(ms, Encoding.UTF8))
                    {
                        message = await reader.ReadToEndAsync();
                    }
                }

                handleMessage(result, message);
            }
        }
Beispiel #10
0
 static async Task<Message> ReceiveAsync(WebSocket ws)
 {
     byte[] buffer = new byte[4096];
     var seg = new ArraySegment<byte>(buffer);
     var result = await ws.ReceiveAsync(seg, CancellationToken.None);
     return Message.Deserialize(new ArraySegment<byte>(buffer, 0, result.Count));
 }
Beispiel #11
0
        protected override async Task <byte[]> Receive(ArraySegment <byte> receiveBuffer, MessageParser parser,
                                                       CancellationToken ct)
        {
            using (var ms = new MemoryStream())
            {
                bool accepted = false;

                WebSocketReceiveResult result;
                int msgSize  = 0;
                int received = 0;
                do
                {
                    result = await _webSocket.ReceiveAsync(receiveBuffer, ct)
                             .ConfigureAwait(false);

                    if (!accepted)
                    {
                        parser.ValidateSize(receiveBuffer, out msgSize);
                        accepted = true;
                    }

                    await ms.WriteAsync(receiveBuffer.Array, 0, result.Count);

                    received += result.Count;
                }while (received < msgSize);

                return(ms.ToArray());
            }
        }
Beispiel #12
0
        private static async Task <string> ReceiveStringAsync(System.Net.WebSockets.WebSocket socket, CancellationToken ct = default(CancellationToken))
        {
            var buffer = new ArraySegment <byte>(new byte[8192]);

            using (var ms = new MemoryStream())
            {
                WebSocketReceiveResult result;
                do
                {
                    ct.ThrowIfCancellationRequested();

                    result = await socket.ReceiveAsync(buffer, ct);

                    ms.Write(buffer.Array, buffer.Offset, result.Count);
                }while (!result.EndOfMessage);

                ms.Seek(0, SeekOrigin.Begin);
                if (result.MessageType != WebSocketMessageType.Text)
                {
                    return(null);
                }

                using (var reader = new StreamReader(ms, Encoding.UTF8))
                {
                    return(await reader.ReadToEndAsync());
                }
            }
        }
Beispiel #13
0
        internal async static Task <MessageData> ReceiveMessage(
            System.Net.WebSockets.WebSocket webSocket,
            CancellationToken ct,
            long maxSize = long.MaxValue)
        {
            ArraySegment <Byte>    buffer = new ArraySegment <byte>(new Byte[ReceiveBufferSize]);
            WebSocketReceiveResult result = null;

            using (var ms = new MemoryStream())
            {
                do
                {
                    result = await webSocket.ReceiveAsync(buffer, ct);

                    ms.Write(buffer.Array, buffer.Offset, result.Count);
                    if (ms.Length > maxSize)
                    {
                        throw new InvalidOperationException("Maximum size of the message was exceeded.");
                    }
                }while (!result.EndOfMessage);

                ms.Seek(0, SeekOrigin.Begin);

                return(new MessageData
                {
                    Data = ms.ToArray(),
                    MessageType = result.MessageType
                });
            }
        }
Beispiel #14
0
 private void keyboardHandler(WebSocket ws)
 {
     byte[] buffer = new byte[4096 * 4096];
     var task = ws.ReceiveAsync(new ArraySegment<byte>(buffer), System.Threading.CancellationToken.None).ContinueWith((ReceiveResult) =>
     {
         string s = System.Text.Encoding.ASCII.GetString(buffer);
         s = s.TrimEnd('\0', ' ');
         foreach (string keyboardCmd in s.Split(' ', '\0'))
         {
             string cmd = keyboardCmd.ToLower().Trim();
             if (keyboardCmd.StartsWith("up/") && keyboardCmd.Length > "up/".Length)
             {
                 Keyboard.KeyUp(int.Parse(keyboardCmd.Substring("up/".Length), System.Globalization.NumberStyles.AllowHexSpecifier));
             }
             if (keyboardCmd.StartsWith("down/") && keyboardCmd.Length > "down/".Length)
             {
                 Keyboard.KeyDown(int.Parse(keyboardCmd.Substring("down/".Length), System.Globalization.NumberStyles.AllowHexSpecifier));
             }
             if (keyboardCmd.StartsWith("tap/") && keyboardCmd.Length > "tap/".Length)
             {
                 Keyboard.KeyTap(int.Parse(keyboardCmd.Substring("tap/".Length), System.Globalization.NumberStyles.AllowHexSpecifier));
             }
         }
         keyboardHandler(ws);
     });
 }
Beispiel #15
0
        /// <summary>
        /// 群发
        /// </summary>
        /// <param name="socketContext"></param>
        /// <returns></returns>
        public async Task ProcessChat(AspNetWebSocketContext socketContext)
        {
            //  SuperSocket:Session
            // 表示客户端发起请求的一个链接
            System.Net.WebSockets.WebSocket socket = socketContext.WebSocket;

            CancellationToken token = new CancellationToken();

            string socketGuid = Guid.NewGuid().ToString();

            OldChatManager.AddUser(socketGuid, UserName, socket, token);

            await OldChatManager.SengdMessage(token, UserName, "进入聊天室");

            while (socket.State == WebSocketState.Open)
            {
                ArraySegment <byte>    buffer = new ArraySegment <byte>(new byte[2048]);
                WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, token);

                string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); // 来自于客户端发送过来的消息内容

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    OldChatManager.RemoveUser(socketGuid);
                    await OldChatManager.SengdMessage(token, UserName, "离开聊天室");

                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, token);
                }
                else
                {
                    await OldChatManager.SengdMessage(token, UserName, userMessage);
                }
            }
        }
Beispiel #16
0
        public async Task EchoAsync(WebSocket webSocket)
        {
            var buffer = new ArraySegment<byte>(new byte[8192]);
            for (; ;)
            {
                var result = await webSocket.ReceiveAsync(
                    buffer,
                    CancellationToken.None);

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    return;
                }
                else if (result.MessageType == WebSocketMessageType.Text)
                {
                    Console.WriteLine("{0}", System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count));
                }

                await webSocket.SendAsync(
                    new ArraySegment<byte>(buffer.Array, 0, result.Count),
                    result.MessageType,
                    result.EndOfMessage,
                    CancellationToken.None);
            }
        }
        private WebSocketHost(WebSocket webSocket)
        {
            _webSocket = webSocket;
            _buffer = new byte[1024];

            // Start listening for incoming messages
            _webSocket.ReceiveAsync(new ArraySegment<byte>(_buffer), CancellationToken.None).ContinueWith(ReceiveMessage);
        }
Beispiel #18
0
        public async Task <string> RecieveMessageAsync(HttpContext context, System.Net.WebSockets.WebSocket socket, CancellationToken token)
        {
            var buffer = new byte[1024 * 4];

            using (_Logger.BeginScope($"Recieving message from socket with state {socket.State}", socket))
            {
                WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), token);
            }
            return(Encoding.UTF8.GetString(buffer));
        }
Beispiel #19
0
        public async Task <T> RecieveItemAsync <T>(System.Net.WebSockets.WebSocket socket, CancellationToken token)
        {
            var buffer = new byte[1024 * 4];

            using (_Logger.BeginScope($"Recieving message from socket with state {socket.State}", socket))
            {
                WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), token);
            }
            return(JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(buffer)));
        }
        //public async Task<string> ReceiveStringAsync(System.Net.WebSockets.WebSocket webSocket)
        //{
        //    var buffer = new ArraySegment<byte>(new byte[8192]);
        //    WebSocketReceiveResult result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
        //    while (!result.CloseStatus.HasValue)
        //    {
        //        //await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

        //        result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
        //    }
        //}

        private async Task <string> ReceiveStringAsync(System.Net.WebSockets.WebSocket socket)
        {
            var buffer = new ArraySegment <byte>(new byte[8192]);
            var result = await socket.ReceiveAsync(buffer, CancellationToken.None);

            while (!result.EndOfMessage)
            {
                result = await socket.ReceiveAsync(buffer, default(CancellationToken));
            }

            //var json = Encoding.UTF8.GetString(buffer.Array);
            //json = json.Replace("\0", "").Trim();
            //return json;

            //ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[8192]);
            //WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
            string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);

            return(userMessage);
        }
Beispiel #21
0
        private static async Task ListenToClients(HttpContext context, System.Net.WebSockets.WebSocket socket)
        {
            var buffer = new byte[6 * 1024];
            WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                var content = Encoding.UTF8.GetString(buffer).Substring(0, result.Count);

                try
                {
                    CallServerMethod(content);
                }
                catch { }

                result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }

            await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
Beispiel #22
0
        private async Task Receive(System.Net.WebSockets.WebSocket socket, Action <WebSocketReceiveResult, byte[]> handleMessage)
        {
            var buffer = new byte[1024 * 4];

            while (socket.State == WebSocketState.Open)
            {
                var result = await socket.ReceiveAsync(buffer : new ArraySegment <byte>(buffer),
                                                       cancellationToken : CancellationToken.None);

                handleMessage(result, buffer);
            }
        }
        public async Task <Tuple <ArraySegment <byte>, WebSocketMessageType> > ReceiveMessage(int maxMessageSize, CancellationToken cancelToken)
        {
            var buffer = new ArraySegment <byte>(new byte[1024 * 8]);
            var result = await mWebSocket.ReceiveAsync(buffer, cancelToken);

            if (result.EndOfMessage)
            {
                return(Tuple.Create(new ArraySegment <byte>(buffer.Array, 0, result.Count), result.MessageType));
            }

            var stream = new MemoryStream(1024 * 8);

            stream.Write(buffer.Array, 0, result.Count);
            var opType = result.MessageType;

            do
            {
                result = await mWebSocket.ReceiveAsync(buffer, cancelToken);

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

                if (stream.Length > maxMessageSize && !result.EndOfMessage)
                {
                    // ignore rest of incoming message
                    do
                    {
                        result = await mWebSocket.ReceiveAsync(buffer, cancelToken);
                    }while (!result.EndOfMessage);
                    throw new InternalBufferOverflowException(
                              "The Buffer is to small to get the Websocket Message! Increase in the Constructor!");
                }
            }while (!result.EndOfMessage);

            stream.Seek(0, SeekOrigin.Begin);
            buffer = new ArraySegment <byte>(new byte[stream.Length]);
            stream.Read(buffer.Array, 0, (int)stream.Length);

            return(Tuple.Create(buffer, opType));
        }
Beispiel #24
0
        public async Task ProcessWebSocket(HttpContext context, WebSocket webSocket)
        {
            var connection = new Connection(context, webSocket);
            _allConnections.Add(connection);
            Console.WriteLine("Connect: {0}", context.Connection.RemoteIpAddress);

            var cancelToken = CancellationToken.None;
            var buffer = new byte[1024];
            WebSocketReceiveResult received =
                await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);

            while (!webSocket.CloseStatus.HasValue)
            {
                string text = System.Text.Encoding.UTF8.GetString(buffer, 0, received.Count);

                Console.WriteLine("Recd: {0}", text);

                try
                {
                    var cmd = Cmd.Parse(text, connection);
                    if (cmd != null) {
                        // TODO: Remove these dependencies from Cmd
                        cmd.SpawnDaemon = _spawnDaemon;
                        cmd.DecayDaemon = _decayDaemon;
                        cmd.Run();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unhandled exception: {0}", ex);
                }

                received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);
            }

            _allConnections.Remove(connection);
            await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, cancelToken);
        }
Beispiel #25
0
        public async Task <Tuple <ArraySegment <byte>, WebSocketMessageType> > ReceiveMessage(byte[] buffer, CancellationToken cancelToken)
        {
            var count = 0;
            WebSocketReceiveResult result;

            do
            {
                var segment = new ArraySegment <byte>(buffer, count, buffer.Length - count);
                result = await mWebSocket.ReceiveAsync(segment, cancelToken);

                count += result.Count;
            }while (!result.EndOfMessage);

            return(new Tuple <ArraySegment <byte>, WebSocketMessageType>(new ArraySegment <byte>(buffer, 0, count), result.MessageType));
        }
        private async Task Receive(System.Net.WebSockets.WebSocket socket, Action <WebSocketReceiveResult, byte[]> handleMessage)
        {
            try
            {
                var buffer = new byte[WebSocketManager.WebSocketBufferSize];
                while (socket.State == WebSocketState.Open)
                {
                    var result = await socket.ReceiveAsync(buffer : new ArraySegment <byte>(buffer), cancellationToken : CancellationToken.None);

                    handleMessage(result, buffer);
                }
            }
            catch
            {
                await WebSocketHub.OnDisconnectedAsync(WebSocketHub.WSManager?.GetId(socket));
            }
        }
Beispiel #27
0
        private static async Task <WSMessage> ReceiveStreamAsync(System.Net.WebSockets.WebSocket socket, ArraySegment <byte> buffer, CancellationToken ct = default(CancellationToken))
        {
            using (var ms = new MemoryStream()) {
                WebSocketReceiveResult result;
                do
                {
                    result = await socket.ReceiveAsync(buffer, ct);

                    ms.Write(buffer.Array, buffer.Offset, result.Count);
                }while (!result.EndOfMessage);

                ms.Seek(0, SeekOrigin.Begin);

                var msg = ProtoBuf.Serializer.Deserialize <WSMessage>(ms);
                return(msg);
            }
        }
Beispiel #28
0
        private async Task DoRespond(WebSocketContext context)
        {
            if (!Global.sockets.ContainsKey(context.SecWebSocketKey))
            {
                Global.sockets.TryAdd(context.SecWebSocketKey, context.WebSocket);
            }

            //foreach (var item in Global.sockets)
            //{
            System.Net.WebSockets.WebSocket socket = context.WebSocket;
            while (true)
            {
                try
                {
                    ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[1024]);

                    WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                    string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                    if (socket.State == WebSocketState.Open)
                    {
                        if (!userMessage.StartsWith("b:"))
                        {
                            userMessage = string.Format("Message : {0}", userMessage);

                            buffer = new ArraySegment <byte>(Encoding.UTF8.GetBytes(userMessage));
                            await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                        }
                        else
                        {
                            userMessage = string.Format("Message : {0}", userMessage);
                            await Broadcast(userMessage);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            //}
        }
        private async Task ProcessProtoBufDecodeRecode(AspNetWebSocketContext context)
        {
            System.Net.WebSockets.WebSocket socket = context.WebSocket;
            while (true)
            {
                ArraySegment <byte>    buffer = new ArraySegment <byte>(new byte[1024]);
                WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                var inputStream = new System.IO.MemoryStream(buffer.Array, buffer.Offset, buffer.Count);

                TestObject msg = Serializer.Deserialize <TestObject>(inputStream);

                if (socket.State == WebSocketState.Open)
                {
                    msg.Name      = "now I change you";
                    msg.TestId    = 12;
                    msg.IsWorking = true;
                    msg.Priority  = Priority.HIGH;
                    msg.Balance   = 876.54321;
                    msg.Contacts.Add(new Contact
                    {
                        Name           = "Jo",
                        ContactDetails = "*****@*****.**"
                    });
                    msg.Contacts.Add(new Contact
                    {
                        Name           = "Fred",
                        ContactDetails = "01234121412"
                    });

                    ArraySegment <byte> outputBuffer;

                    using (var serializationBuffer = new System.IO.MemoryStream())
                    {
                        Serializer.Serialize(serializationBuffer, msg);
                        outputBuffer = new ArraySegment <byte>(serializationBuffer.GetBuffer(), 0, (int)serializationBuffer.Length);
                    }

                    await socket.SendAsync(outputBuffer, WebSocketMessageType.Binary, true, CancellationToken.None);
                }
                else
                {
                    break;
                }
            }
        }
Beispiel #30
0
        private async Task Receive(System.Net.WebSockets.WebSocket socket, Action <WebSocketReceiveResult, byte[]> handleMessage)
        {
            var receiveBuffer = new byte[1024 * 4];

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

                    handleMessage(result, receiveBuffer);
                }
            }
            catch (WebSocketException wsex) when(wsex.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
            {
                Console.WriteLine("ConnectionClosedPrematurely");
            }
        }
Beispiel #31
0
        private async Task Receive(System.Net.WebSockets.WebSocket socket, Action <WebSocketReceiveResult, byte[]> handleMessage)
        {
            try
            {
                var buffer = new byte[1024 * 4];
                while (socket.State == WebSocketState.Open)
                {
                    var result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                    handleMessage(result, buffer);
                }
                await WebSocketHandler.OnDisconnected(socket);
            }
            catch
            {
                // ignored
            }
        }
        private async Task KeepAlive(WebSocket connection)
        {
            while (connection.State == WebSocketState.Open)
            {
                var token = CancellationToken.None;
                var buffer = new ArraySegment<byte>(new byte[4096]);
                var received = await connection.ReceiveAsync(buffer, token);

                switch (received.MessageType)
                {
                    case WebSocketMessageType.Text:
                        var request = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
                        SocketMessage receive = JsonConvert.DeserializeObject<SocketMessage>(request);
                        await Map.Receive(receive);
                        break;
                }
            }
        }
Beispiel #33
0
        private async Task DoPull(WebSocket socket, CancellationToken cancellationToken)
        {
            try
            {
                var buf = new Byte[4 * 1024];
                while (!cancellationToken.IsCancellationRequested && socket.State == WebSocketState.Open)
                {
                    var data = await socket.ReceiveAsync(new ArraySegment <Byte>(buf), cancellationToken);

                    var cmd = buf.ToStr(null, 0, data.Count).ToJsonEntity <CommandModel>();
                    if (cmd != null)
                    {
                        XTrace.WriteLine("Got Command: {0}", cmd.ToJson());
                        if (cmd.Expire.Year < 2000 || cmd.Expire > DateTime.Now)
                        {
                            switch (cmd.Command)
                            {
                            case "Deploy":
                                // 发布中心通知有应用需要部署,马上执行一次心跳,拉取最新应用信息
                                _ = Task.Run(Ping);
                                break;

                            default:
                                var rs = CommandQueue.Publish(cmd.Command, cmd);
                                if (rs != null)
                                {
                                    await ReportAsync(cmd.Id, rs);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }

            if (socket.State == WebSocketState.Open)
            {
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "finish", default);
            }
        }
Beispiel #34
0
        public async Task <byte[]> ReadBytesAsync(System.Net.WebSockets.WebSocket websocket, CancellationToken cancellationToken)
        {
            WebSocketReceiveResult result;
            var buffer = new ArraySegment <byte>(new byte[8192]);
            int length = 0;

            do
            {
                result = await websocket.ReceiveAsync(buffer, cancellationToken);

                if (result.CloseStatus != null)
                {
                    return(null);
                }
                length += result.Count;
            }while (!result.EndOfMessage);

            return(buffer.Array.Take(length).ToArray());
        }
Beispiel #35
0
        private async Task Receive(System.Net.WebSockets.WebSocket socket, Action <WebSocketReceiveResult, byte[]> handleMessage)
        {
            try
            {
                var buffer = new byte[1024 * 4];

                while (socket.State == WebSocketState.Open)
                {
                    var result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer),
                                                           CancellationToken.None);

                    handleMessage(result, buffer);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(null, ex);
            }
        }
        private async Task HandleWebSocket(WebSocketContext wsContext)
        {
            var socketId = Guid.NewGuid().ToString();

            System.Net.WebSockets.WebSocket webSocket = wsContext.WebSocket;
            try
            {
                _sockets.TryAdd(socketId, webSocket);
                byte[] receiveBuffer = new byte[1024 * 4];
                while (webSocket.State == WebSocketState.Open)
                {
                    //var msg = Encoding.UTF8.GetBytes(WebSocketSerivce.GetNewOrders());
                    //await webSocket.SendAsync(new ArraySegment<byte>(msg, 0, msg.Length), WebSocketMessageType.Text,
                    //    true, CancellationToken.None);

                    WebSocketReceiveResult receiveResult =
                        await webSocket.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), CancellationToken.None);

                    if (receiveResult.MessageType == WebSocketMessageType.Close)
                    {
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);

                        _sockets.TryRemove(socketId, out System.Net.WebSockets.WebSocket removedSocket);
                    }
                    else
                    {
                        foreach (var socket in _sockets.Where(x => x.Key != socketId).Select(x => x.Value))
                        {
                            await socket.SendAsync(new ArraySegment <byte>(receiveBuffer, 0, receiveResult.Count),
                                                   WebSocketMessageType.Text, receiveResult.EndOfMessage, CancellationToken.None);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e);
            }
            finally
            {
                webSocket?.Dispose();
            }
        }
Beispiel #37
0
        internal async Task <Packet> ReceiveAsync()
        {
            if (Closed)
            {
                return(null);
            }

            var result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            if (result.CloseStatus.HasValue)
            {
                this.closed = true;
                await this.socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);

                return(null);
            }

            return(packetDataSerializer.Deserialize(buffer, 0, result.Count, result.MessageType, result.EndOfMessage));
        }
Beispiel #38
0
        internal async Task RunAsync()
        {
            await _logger.InfoAsync($"Connected");

            var token = _cancelToken.Token;

            try
            {
                var segment = new ArraySegment <byte>(_inBuffer);

                //Send HELLO
                await SendAsync(GatewayOpCode.Hello, new HelloEvent { HeartbeatInterval = 15000 }).ConfigureAwait(false);

                while (_socket.State == WebSocketState.Open)
                {
                    var result = await _socket.ReceiveAsync(segment, token).ConfigureAwait(false);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await _logger.WarningAsync($"Received Close {result.CloseStatus} ({result.CloseStatusDescription ?? "No Reason"})").ConfigureAwait(false);
                    }
                    else
                    {
                        await _logger.InfoAsync($"Received {result.Count} bytes");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                try { await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).ConfigureAwait(false); }
                catch { }
            }
            catch (Exception ex)
            {
                try { await _socket.CloseAsync(WebSocketCloseStatus.InternalServerError, ex.Message, CancellationToken.None).ConfigureAwait(false); }
                catch { }
            }
            finally
            {
                await _logger.InfoAsync($"Disconnected");
            }
        }
Beispiel #39
0
        async Task websocketHandle(System.Net.WebSockets.WebSocket socket, HttpRequest request)
        {
            var bs = new byte[204800];

            while (true)
            {
                if (socket.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    try
                    {
                        ArraySegment <byte>    buffer = new ArraySegment <byte>(bs);
                        WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                        if (result.Count == 0)
                        {
                            //客户端要求关闭
                            socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).Wait();
                            continue;
                        }
                        StringBuilder str = new StringBuilder();
                        foreach (var item in request.Headers)
                        {
                            foreach (var v in item.Value)
                            {
                                str.Append($"{item.Key}={v}\r\n");
                            }
                        }
                        byte[] sendbackBs = System.Text.Encoding.UTF8.GetBytes(str.ToString());

                        buffer = new ArraySegment <byte>(sendbackBs);
                        await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    break;
                }
            }
        }
Beispiel #40
0
        private async Task DoRespond(AspNetWebSocketContext context)
        {
            System.Net.WebSockets.WebSocket socket = context.WebSocket;
            while (true)
            {
                ArraySegment <byte>    buffer = new ArraySegment <byte>(new byte[1024]);
                WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                if (socket.State == WebSocketState.Open)
                {
                    string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                    userMessage = "Message from client : " + userMessage;
                    buffer      = new ArraySegment <byte>(Encoding.UTF8.GetBytes(userMessage));
                    await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                else
                {
                    break;
                }
            }
        }
Beispiel #41
0
        private static async Task WebSocketToPipeWorker(WebSocket socket, IMessagePipeEnd pipe, CancellationToken cancellationToken) {
            const int blockSize = 0x10000;
            var buffer = new MemoryStream(blockSize);

            while (true) {
                cancellationToken.ThrowIfCancellationRequested();

                int index = (int)buffer.Length;
                buffer.SetLength(index + blockSize);

                var wsrr = await socket.ReceiveAsync(new ArraySegment<byte>(buffer.GetBuffer(), index, blockSize), cancellationToken);
                buffer.SetLength(index + wsrr.Count);

                if (wsrr.CloseStatus != null) {
                    break;
                } else if (wsrr.EndOfMessage) {
                    pipe.Write(buffer.ToArray());
                    buffer.SetLength(0);
                }
            }
        }
        private async Task ReceiveAsync(System.Net.WebSockets.WebSocket webSocket, CancellationToken disconnectToken)
        {
            bool closedReceived = false;
            var  buffer         = new byte[4096];

            try
            {
                while (!disconnectToken.IsCancellationRequested && !closedReceived)
                {
                    var arraySegment = new ArraySegment <byte>(buffer);
                    var result       = await webSocket.ReceiveAsync(arraySegment, disconnectToken);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        closedReceived = true;
                        await Task.WhenAny(CloseAsync(), Task.Delay(_closeTimeout));
                    }
                    if (result.MessageType == WebSocketMessageType.Text)
                    {
                        OnMessage(Encoding.UTF8.GetString(arraySegment.Array.Take(result.Count).ToArray()));
                    }
                    else if (result.MessageType == WebSocketMessageType.Binary)
                    {
                        OnMessage(arraySegment.Array.Take(result.Count).ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error Receiving : " + ex.Message);
            }
            try
            {
                await CloseAsync();
            }
            finally
            {
                OnClosed();
            }
        }
Beispiel #43
0
        private static async Task DoWebSocketReceiveSendAsync(WebSocket receiver, WebSocket sender, CancellationToken ct) {
            if (receiver == null || sender == null) {
                return;
            }

            ArraySegment<byte> receiveBuffer = new ArraySegment<byte>(new byte[65335]);
            while (receiver.State == WebSocketState.Open && sender.State == WebSocketState.Open) {
                if (ct.IsCancellationRequested) {
                    receiver.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", CancellationToken.None).SilenceException<WebSocketException>().DoNotWait();
                    sender.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", CancellationToken.None).SilenceException<WebSocketException>().DoNotWait();
                    return;
                }

                WebSocketReceiveResult result = await receiver.ReceiveAsync(receiveBuffer, ct);

                byte[] data = await receiveBuffer.ToByteArrayAsync(result.Count);
                ArraySegment<byte> sendBuffer = new ArraySegment<byte>(data);
                await sender.SendAsync(sendBuffer, result.MessageType, result.EndOfMessage, ct);

                if (result.MessageType == WebSocketMessageType.Close) {
                    await receiver.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", ct);
                }
            }
        }
        private async Task<String> ReadSerializedMessage(WebSocket socket)
        {
            var byteBuffer = new byte[MaxBufferSize];
            var arraySegmentBuffer = new ArraySegment<byte>(byteBuffer);
            WebSocketReceiveResult result = await socket.ReceiveAsync(arraySegmentBuffer, CancellationToken.None);
            string ret = "";

            if (result.MessageType == WebSocketMessageType.Close)
            {
                await
                    socket.CloseAsync(result.CloseStatus.GetValueOrDefault(), result.CloseStatusDescription,
                        CancellationToken.None);
            }
            else
            {
                int messageSize = 0;

                for (messageSize = result.Count; !result.EndOfMessage; messageSize += result.Count)
                {
                    result = await socket.ReceiveAsync(new ArraySegment<byte>(byteBuffer, messageSize, MaxBufferSize - messageSize), CancellationToken.None);
                }
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    ret = Encoding.UTF8.GetString(byteBuffer, 0, messageSize);
                }
            }
            return ret;
        }
        private async Task CopyFromWebSocketToStreamWorker(WebSocket webSocket, Stream stream, CancellationToken ct) {
            var buffer = new ArraySegment<byte>(new byte[0x10000]);
            while (webSocket.State == WebSocketState.Open) {
                ct.ThrowIfCancellationRequested();

                Log("WS -> TCP: waiting for packet.");
                var recv = await webSocket.ReceiveAsync(buffer, ct);
                Log("WS -> TCP: received packet:\n{0}", Encoding.UTF8.GetString(buffer.Array, 0, recv.Count));

                await stream.WriteAsync(buffer.Array, 0, recv.Count, ct);
                Log("WS -> TCP: packet relayed.");
            }
        }
        /// <summary>
        /// WebSocket監聽主程序
        /// </summary>
        /// <param name="Context">Http通訊內容</param>
        /// <param name="Socket">WebSocket物件</param>
        protected async Task Listen(HttpContext Context, WebSocket Socket) {
            OnConnected?.Invoke(Context, Socket);
            
            while (true) {
                bool ReceiveComplete = true;
                WebSocketReceiveResult ReceiveResult = null;
                List<byte> ReceiveData = new List<byte>();
                
                //循環接收資料以防資料大於緩衝區大小時分段傳輸
                do {
                    //建立緩衝區
                    byte[] Buffer = new byte[BufferSize];

                    //接收資料
                    ReceiveResult = await Socket.ReceiveAsync(new ArraySegment<byte>(Buffer), CancellationToken.None);

                    //乾淨資料
                    byte[] ClearData = new byte[ReceiveResult.Count];

                    //複製本次傳輸範圍資料
                    Array.Copy(Buffer, ClearData, ReceiveResult.Count);

                    //存入接收資料集合
                    ReceiveData.AddRange(ClearData);

                    //檢查是否接收完成
                    ReceiveComplete = !ReceiveResult.EndOfMessage;
                } while (ReceiveComplete);

                //檢查是否關閉連線,如關閉則跳脫循環監聽
                if (ReceiveResult.CloseStatus.HasValue)break;

                OnReceive?.Invoke(Socket, ReceiveResult.MessageType, ReceiveData.ToArray());
            };

            OnDisconnected?.Invoke(Context, Socket);
        }
Beispiel #47
0
        private void mouseHandler(WebSocket ws)
        {
            byte[] buffer = new byte[4096 * 4096];
            var task = ws.ReceiveAsync(new ArraySegment<byte>(buffer), System.Threading.CancellationToken.None).ContinueWith((ReceiveResult) =>
            {
                string s = System.Text.Encoding.ASCII.GetString(buffer);
                s = s.TrimEnd('\0', ' ');
                foreach (string mouseCmd in s.Split(' ', '\0'))
                {
                    string cmd = mouseCmd.ToLower().Trim();
                    if (mouseCmd == "reset/")
                    {
                        Mouse.SetCursorPos(500, 500);
                    }
                    if (mouseCmd.StartsWith("click/"))
                    {
                        switch (int.Parse(mouseCmd.Substring("click/".Length)))
                        {
                            case 0:
                                Mouse.LeftClick();
                                break;

                            case 1:
                                Mouse.RightClick();
                                break;

                            case 2:
                                Mouse.MiddleClick();
                                break;
                        }
                    }
                    if (mouseCmd.StartsWith("position/"))
                    {
                        String[] stringArray = mouseCmd.Substring("position/".Length).Split('/');
                        Mouse.SetCursorPos(int.Parse(stringArray[0]), int.Parse(stringArray[1]));
                    }
                    if (mouseCmd.StartsWith("up/"))
                    {
                        switch (int.Parse(mouseCmd.Substring("up/".Length)))
                        {
                            case 0:
                                Mouse.LeftUp();
                                break;

                            case 1:
                                Mouse.RightUp();
                                break;

                            case 2:
                                Mouse.MiddleUp();
                                break;
                        }
                    }
                    if (mouseCmd.StartsWith("down/"))
                    {
                        switch (int.Parse(mouseCmd.Substring("down/".Length)))
                        {
                            case 0:
                                Mouse.LeftDown();
                                break;

                            case 1:
                                Mouse.RightDown();
                                break;

                            case 2:
                                Mouse.MiddleDown();
                                break;
                        }
                    }
                }
                mouseHandler(ws);
            });
        }
        public static async Task<WebSocketMessage> ReadMessageAsync(WebSocket webSocket, int bufferSize, int? maxMessageSize, CancellationToken disconnectToken)
        {
            WebSocketMessage message;

            // Read the first time with an empty array
            WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(_emptyArraySegment, disconnectToken).PreserveCultureNotContext();

            if (TryGetMessage(receiveResult, null, out message))
            {
                return message;
            }

            var buffer = new byte[bufferSize];

            // Now read with the real buffer
            var arraySegment = new ArraySegment<byte>(buffer);

            receiveResult = await webSocket.ReceiveAsync(arraySegment, disconnectToken).PreserveCultureNotContext();

            if (TryGetMessage(receiveResult, buffer, out message))
            {
                return message;
            }
            else
            {
                // for multi-fragment messages, we need to coalesce
                ByteBuffer bytebuffer = new ByteBuffer(maxMessageSize);
                bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                WebSocketMessageType originalMessageType = receiveResult.MessageType;

                while (true)
                {
                    // loop until an error occurs or we see EOF
                    receiveResult = await webSocket.ReceiveAsync(arraySegment, disconnectToken).PreserveCultureNotContext();

                    if (receiveResult.MessageType == WebSocketMessageType.Close)
                    {
                        return WebSocketMessage.CloseMessage;
                    }

                    if (receiveResult.MessageType != originalMessageType)
                    {
                        throw new InvalidOperationException("Incorrect message type");
                    }

                    bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));

                    if (receiveResult.EndOfMessage)
                    {
                        switch (receiveResult.MessageType)
                        {
                            case WebSocketMessageType.Binary:
                                return new WebSocketMessage(bytebuffer.GetByteArray(), WebSocketMessageType.Binary);

                            case WebSocketMessageType.Text:
                                return new WebSocketMessage(bytebuffer.GetString(), WebSocketMessageType.Text);

                            default:
                                throw new InvalidOperationException("Unknown message type");
                        }
                    }
                }
            }
        }
 // Web sockets start off as minimal HTTP connections, upgrade, and then behave like TCP sockets for the most part.
 // Thus the 'security service' abstraction is used to insulate this listener from direct TCP objects dependence.
 // Somewhat of a cheat, but it is the way it is :-)!
 private async Task CheckHeaders(WebSocket socket) {
     byte[] buffer = new byte[Config.Get(Constants.Configuration.MaxPayloadLength)];
     var response = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.Token);
     // TODO: Ensure complete message is received
     var result = Encoding.ASCII.GetString(buffer, 0, response.Count);
     LogFacade.Instance.LogDebug("Received headers for web socket verification: " + result);
     SecurityService.DissectAndValidateFrame(result);
 }
        public static async Task<WebSocketMessage> ReadMessageAsync(WebSocket webSocket, byte[] buffer, int maxMessageSize, CancellationToken disconnectToken)
        {
            var arraySegment = new ArraySegment<byte>(buffer);
            WebSocketReceiveResult receiveResult = null;

            try
            {
                receiveResult = await webSocket.ReceiveAsync(arraySegment, disconnectToken).ConfigureAwait(continueOnCapturedContext: false);
            }
            catch (Exception)
            {
                // If the websocket is aborted while we're reading then just rethrow
                // an operaton cancelled exception so the caller can handle it
                // appropriately
                if (webSocket.State == WebSocketState.Aborted)
                {
                    throw new OperationCanceledException();
                }
                else
                {
                    // Otherwise rethrow the original exception
                    throw;
                }
            }

            // special-case close messages since they might not have the EOF flag set
            if (receiveResult.MessageType == WebSocketMessageType.Close)
            {
                return new WebSocketMessage(null, WebSocketMessageType.Close);
            }

            if (receiveResult.EndOfMessage)
            {
                // we anticipate that single-fragment messages will be common, so we optimize for them
                switch (receiveResult.MessageType)
                {
                    case WebSocketMessageType.Binary:
                        return new WebSocketMessage(BufferSliceToByteArray(buffer, receiveResult.Count), WebSocketMessageType.Binary);

                    case WebSocketMessageType.Text:
                        return new WebSocketMessage(BufferSliceToString(buffer, receiveResult.Count), WebSocketMessageType.Text);

                    default:
                        throw new Exception("This code path should never be hit.");
                }
            }
            else
            {
                // for multi-fragment messages, we need to coalesce
                ByteBuffer bytebuffer = new ByteBuffer(maxMessageSize);
                bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                WebSocketMessageType originalMessageType = receiveResult.MessageType;

                while (true)
                {
                    // loop until an error occurs or we see EOF
                    receiveResult = await webSocket.ReceiveAsync(arraySegment, disconnectToken).ConfigureAwait(continueOnCapturedContext: false);
                    if (receiveResult.MessageType != originalMessageType)
                    {
                        throw new InvalidOperationException("Incorrect message type");
                    }

                    bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                    if (receiveResult.EndOfMessage)
                    {
                        switch (receiveResult.MessageType)
                        {
                            case WebSocketMessageType.Binary:
                                return new WebSocketMessage(bytebuffer.GetByteArray(), WebSocketMessageType.Binary);

                            case WebSocketMessageType.Text:
                                return new WebSocketMessage(bytebuffer.GetString(), WebSocketMessageType.Text);

                            default:
                                throw new Exception("This code path should never be hit.");
                        }
                    }
                }
            }
        }
 private static WebSocketReceiveAsync WebSocketReceiveAsync(WebSocket webSocket)
 {
     return async (buffer, cancel) =>
     {
         var nativeResult = await webSocket.ReceiveAsync(buffer, cancel);
         return new WebSocketReceiveResultTuple(
             EnumToOpCode(nativeResult.MessageType),
             nativeResult.EndOfMessage,
             (nativeResult.MessageType == WebSocketMessageType.Close ? null : (int?)nativeResult.Count),
             (int?)nativeResult.CloseStatus,
             nativeResult.CloseStatusDescription);
     };
 }
        private static async void WebSocketServer()
        {

            HttpListener listener = new HttpListener();

            listener.Prefixes.Add("http://localhost:3696/websocket/");
            listener.Start();
            bool wasOpen = false;

            while (listener.IsListening)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;

                if (request.IsWebSocketRequest)
                {
                    WebSocketContext webCont = await context.AcceptWebSocketAsync(subProtocol: null);
                    ws = webCont.WebSocket;

                    byte[] receivebytes = new byte[1024];

                    while (ws.State == WebSocketState.Open)
                    {

                        WebSocketReceiveResult rcRes = await ws.ReceiveAsync(new ArraySegment<byte>(receivebytes), CancellationToken.None);
                        string receivedString = Encoding.UTF8.GetString(receivebytes, 0, rcRes.Count);
                        Console.WriteLine("RECEIVED: " + receivedString);
                        wasOpen = true;
                        Thread.Sleep(1);
                    }

                    if (ws.State != WebSocketState.Open && wasOpen)
                    {
                        Console.WriteLine("Websocket closed");
                        exit();
                        break;
                    }

                }
                Thread.Sleep(1);
            }

        }
Beispiel #53
0
        private static async Task<WebSocketReceiveResult> GetWebSocket(WebSocket webSocket, ArraySegment<byte> buffer)
        {
            WebSocketReceiveResult result;

            try
            {
                result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
            }
            catch (Exception ex)
            {
                logger.LogVerbose("Exception in GetWebSocket: {0}", ex.Message);

                result = new WebSocketReceiveResult(buffer.Count, WebSocketMessageType.Text, false, WebSocketCloseStatus.ProtocolError, "ReceiveAsync error");
            }

            return result;
        }
Beispiel #54
0
    private static async Task<string> ReceiveMessageAsync(WebSocket socket, CancellationToken cancel)
    {
      using (var stream = new MemoryStream())
      {
        var buffer = ClientWebSocket.CreateServerBuffer(1024);
        WebSocketReceiveResult received;

        do
        {
          received = await socket.ReceiveAsync(buffer, cancel);

          stream.Write(buffer.Array, buffer.Offset, received.Count);
        }
        while (!received.EndOfMessage);

        stream.Position = 0;

        using (var reader = new StreamReader(stream, Encoding.UTF8))
        {
          return reader.ReadToEnd();
        }
      }
    }
Beispiel #55
0
    private static async Task ReceiveCloseMessageAsync(WebSocket socket, CancellationToken cancel)
    {
      var buffer = ClientWebSocket.CreateServerBuffer(1024);
      var received = await socket.ReceiveAsync(buffer, cancel);

      if (received.MessageType != WebSocketMessageType.Close)
      {
        throw new InvalidOperationException();
      }
    }
        public static async Task<WebSocketMessage> ReadMessageAsync(WebSocket webSocket, MemoryPool _memoryPool, int bufferSize, int? maxMessageSize, CancellationToken disconnectToken)
        {
            WebSocketMessage message;

            // Read the first time with an empty array
            //      Holds hear untill first message comes through. Because its empty, it will go onto the next 
            //      TryGetMessage when the data comes through.
            var receiveResult = await webSocket.ReceiveAsync(_emptyArraySegment, disconnectToken).PreserveCultureNotContext();
            if (TryGetMessage(receiveResult, null, out message))
            {
                return message;
            }
            
            var arraySegment = _memoryPool.AllocSegment(bufferSize);

            // Now read with the real buffer
            //      We now know there is content, so we we allocate memory. Additionally this is setup in hopes
            //      that the first message we read will only take one read.
            receiveResult = await webSocket.ReceiveAsync(arraySegment, disconnectToken).PreserveCultureNotContext();
            if (TryGetMessage(receiveResult, arraySegment.Array, out message))
            {
                return message;
            }

            // Lastly read the rest of the message if needed
            //      For multi-fragment messages, we need to coalesce and use a buffer that can grow in size 
            //      as more of the message comes in.
            var bytebuffer = new ByteBuffer(maxMessageSize);
            bytebuffer.Append(BufferSliceToByteArray(arraySegment.Array, receiveResult.Count));
            var originalMessageType = receiveResult.MessageType;

            while (true)
            {
                // loop until an error occurs or we see EOF
                receiveResult = await webSocket.ReceiveAsync(arraySegment, disconnectToken).PreserveCultureNotContext();

                if (receiveResult.MessageType == WebSocketMessageType.Close)
                {
                    return WebSocketMessage.CloseMessage;
                }

                if (receiveResult.MessageType != originalMessageType)
                {
                    throw new InvalidOperationException("Incorrect message type");
                }

                bytebuffer.Append(BufferSliceToByteArray(arraySegment.Array, receiveResult.Count));

                if (receiveResult.EndOfMessage)
                {
                    switch (receiveResult.MessageType)
                    {
                        case WebSocketMessageType.Binary:
                            return new WebSocketMessage(bytebuffer.GetByteArray(), WebSocketMessageType.Binary);

                        case WebSocketMessageType.Text:
                            return new WebSocketMessage(bytebuffer.GetString(), WebSocketMessageType.Text);

                        default:
                            throw new InvalidOperationException("Unknown message type");
                    }
                }
            }
        }