private void ParseFrame(NetworkDataEventArgs e)
        {
            var data = new List <byte>();
            var payloadStartIndex = 2 + _parser.PayloadLenLenght + _parser.MaskingKeyLenght;

            switch ((WebSocketOpcode)_parser.Opcode)
            {
            case WebSocketOpcode.Ping:
                //Ping frame. Sent Pong Frame.
                _parser.PollReceived = true;
                data.AddRange(_parser.DataBuffer);
                data[0] = (byte)(data[0] & 0xF0);
                data[0] = (byte)(data[0] | (byte)WebSocketOpcode.Pong);
                Write(data.ToArray());
                break;

            case WebSocketOpcode.Pong:
                _parser.PollReceived = true;
                break;

            case WebSocketOpcode.ConnectionClose:
                //Close frame. Sent Close back.
                var connectionCloseReason = (_parser.DataBuffer[payloadStartIndex] << 8) + ((int)_parser.DataBuffer[payloadStartIndex + 1] << 0);
                ConnectionCloseEvent?.Invoke(this, new ConnectionCloseEventArgs((ConnectionCloseReason)connectionCloseReason));
                SendClose((ConnectionCloseReason)connectionCloseReason);
                break;

            case WebSocketOpcode.BinaryFrame:
            case WebSocketOpcode.TextFrame:
                DataReceivedEvent?.Invoke(this, new DataReceivedEventArgs(e.LocalEndPoint, e.RemoteEndPoint, (WebSocketOpcode)_parser.Opcode, _parser.DataBuffer.GetRange(payloadStartIndex, _parser.PayloadLen).ToArray()));
                break;
            }
        }
Exemple #2
0
        private void C_DataReceivedEvent(object sender, NetworkDataEventArgs e)
        {
            if (_handshakeTest)
            {
                foreach (byte b in e.Data)
                {
                    _networkReceivedString += Encoding.UTF8.GetString(new byte[] { b });

                    if (_networkReceivedString.Contains("\r\n"))
                    {
                        _httpRequest.Add(_networkReceivedString);
                        _networkReceivedString = string.Empty;
                    }

                    if (_httpRequest.Count > 0 && _httpRequest[_httpRequest.Count - 1] == "\r\n")
                    {
                        _networkReceivedString = string.Empty;
                        _handshakeReceived     = true;
                    }
                }
            }
            else
            {
                _clientFrameData.AddRange(e.Data);
            }
        }
Exemple #3
0
 void ClientDataSent(object sender, NetworkDataEventArgs e)
 {
     if (this.DataSent != null)
     {
         this.DataSent(sender, e);
     }
 }
Exemple #4
0
 private void Client_DataReceivedEvent(object sender, NetworkDataEventArgs e)
 {
     if (!ClientDataReceivedEvent.ContainsKey(e.LocalEndPoint.ToString()))
     {
         ClientDataReceivedEvent.Add(e.LocalEndPoint.ToString(), new List <NetworkDataEventArgs>());
     }
     ClientDataReceivedEvent[e.LocalEndPoint.ToString()].Add(e);
 }
Exemple #5
0
 private void Server_DataReceivedEvent(object sender, NetworkDataEventArgs e)
 {
     if (!ServerDataReceivedEvent.ContainsKey(e.RemoteEndPoint.ToString()))
     {
         ServerDataReceivedEvent.Add(e.RemoteEndPoint.ToString(), new List <NetworkDataEventArgs>());
     }
     ServerDataReceivedEvent[e.RemoteEndPoint.ToString()].Add(e);
 }
 protected override void ProcessByteInternal(NetworkDataEventArgs e)
 {
     if (_parser.FirstConnected)
     {
         ParseHandshake(e);
     }
     else
     {
         ParseData(e);
     }
 }
Exemple #7
0
        private void DataReceivedHandler(object sender, NetworkDataEventArgs e)
        {
            if (DataReceived != null)
            {
                DataReceived(sender, e);
            }
            Thread thread = new Thread(new ParameterizedThreadStart(StartProcessingData));

            thread.IsBackground = true;
            object[] objs = new object[2] {
                e.Data, sender
            };
            thread.Start(objs);
        }
Exemple #8
0
 private void Server_SendDataTraceEvent(object sender, NetworkDataEventArgs e)
 {
     ServerSendDataTraceEvent.Add(e);
 }
Exemple #9
0
 private void Client_ReceiveDataTraceEvent(object sender, NetworkDataEventArgs e)
 {
     ClientReceiveDataTraceEvent.Add(e);
 }
Exemple #10
0
 private void Client_SendDataTraceEvent(object sender, NetworkDataEventArgs e)
 {
     ClientSendDataTraceEvent.Add(e);
 }
Exemple #11
0
 private void Server_DataReceivedEvent(object sender, NetworkDataEventArgs e)
 {
     ServerDataReceivedEvent.Add(e);
 }
Exemple #12
0
 private void Client_DataReceivedEvent(object sender, NetworkDataEventArgs e)
 {
     ClientDataReceivedEvent.Add(e);
 }
 protected override void ProcessByteInternal(NetworkDataEventArgs e)
 {
     ReceivedBytes.AddRange(e.Data);
 }
 private void Receiver_ReceiveDataTraceEvent(object sender, NetworkDataEventArgs e)
 {
     ReceiverDataEventArgs = e;
 }
        private void ParseData(NetworkDataEventArgs e)
        {
            foreach (byte b in e.Data)
            {
                if (_parser.IsFirstDataByte)
                {
                    _parser.DataBuffer.Clear();
                    _parser.Fin                = 0;
                    _parser.Opcode             = 0;
                    _parser.Mask               = 0;
                    _parser.PayloadLen1        = 0;
                    _parser.PayloadLen         = 0;
                    _parser.HeaderReceived     = false;
                    _parser.FrameReceived      = false;
                    _parser.PayloadLenReceived = false;
                    _parser.MaskingKey[0]      = 0;
                    _parser.MaskingKey[1]      = 0;
                    _parser.MaskingKey[2]      = 0;
                    _parser.MaskingKey[3]      = 0;
                    _parser.PayloadLenLenght   = 0;
                    _parser.MaskingKeyLenght   = 0;
                }

                _parser.DataBuffer.AddRange(new[] { b });
                _parser.IsFirstDataByte = false;

                if (_parser.DataBuffer.Count == 2)
                {
                    _parser.Fin         = (_parser.DataBuffer[0] & 0x80) >> 7;
                    _parser.Opcode      = (_parser.DataBuffer[0] & 0x0F);
                    _parser.Mask        = (b & 0x80) >> 7;
                    _parser.PayloadLen1 = (b & 0x7F);
                    if (_parser.PayloadLen1 < 126)
                    {
                        _parser.PayloadLen         = _parser.PayloadLen1;
                        _parser.PayloadLenReceived = true;
                        _parser.PayloadLenLenght   = 0;
                    }
                }

                if (_parser.PayloadLenReceived == false)
                {
                    if (_parser.PayloadLen1 == 126 && _parser.DataBuffer.Count == 4)
                    {
                        _parser.PayloadLen         = (_parser.DataBuffer[2] << 8) + _parser.DataBuffer[3];
                        _parser.PayloadLenReceived = true;
                        _parser.PayloadLenLenght   = 2;
                        continue;
                    }
                    if (_parser.PayloadLen1 == 127 && _parser.DataBuffer.Count == 6)
                    {
                        _parser.PayloadLen         = (_parser.DataBuffer[2] << 24) + (_parser.DataBuffer[3] << 16) + (_parser.DataBuffer[4] << 8) + (_parser.DataBuffer[5] << 0);
                        _parser.PayloadLenReceived = true;
                        _parser.PayloadLenLenght   = 4;
                        continue;
                    }
                }
                if (_parser.PayloadLenReceived && _parser.HeaderReceived == false)
                {
                    if (_parser.Mask == 1)
                    {
                        _parser.MaskingKeyLenght = 4;
                        if (_parser.DataBuffer.Count == 2 + _parser.PayloadLenLenght + 4)
                        {
                            _parser.MaskingKey[0]  = _parser.DataBuffer[_parser.DataBuffer.Count - 4];
                            _parser.MaskingKey[1]  = _parser.DataBuffer[_parser.DataBuffer.Count - 3];
                            _parser.MaskingKey[2]  = _parser.DataBuffer[_parser.DataBuffer.Count - 2];
                            _parser.MaskingKey[3]  = _parser.DataBuffer[_parser.DataBuffer.Count - 1];
                            _parser.HeaderReceived = true;
                        }
                    }
                    else
                    {
                        _parser.MaskingKeyLenght = 0;
                        _parser.HeaderReceived   = true;
                    }
                }
                if (_parser.HeaderReceived && _parser.DataBuffer.Count == 2 + _parser.PayloadLenLenght + _parser.MaskingKeyLenght + _parser.PayloadLen)
                {
                    if (_parser.Mask == 1)
                    {
                        var j = 0;
                        for (int i = 2 + _parser.PayloadLenLenght +
                                     _parser.MaskingKeyLenght; i < _parser.DataBuffer.Count; i++, j++)
                        {
                            _parser.DataBuffer[i] = (byte)(_parser.DataBuffer[i] ^ _parser.MaskingKey[j % 4]);
                        }
                    }
                    ParseFrame(e);
                    _parser.IsFirstDataByte = true;
                }
            }
        }
Exemple #16
0
 private void Server_ReceiveDataTraceEvent(object sender, NetworkDataEventArgs e)
 {
     ServerReceiveDataTraceEvent.Add(e);
 }
 private void Sender_SendDataTraceEvent(object sender, NetworkDataEventArgs e)
 {
     SenderDataEventArgs = e;
 }
        protected override void ProcessDataInternal(NetworkDataEventArgs e)
        {
            if (!_endpointDataParsers.ContainsKey(e.RemoteEndPoint))
            {
                _endpointDataParsers.Add(e.RemoteEndPoint, new EndpointDataParser());
            }

            var parser = _endpointDataParsers[e.RemoteEndPoint];

            foreach (byte b in e.Data)
            {
                var barr = new[] { b };
                parser.NetworkReceivedString += Encoding.UTF8.GetString(barr);

                if (parser.ContentLen != -1)
                {
                    parser.ContentIndex++;
                    parser.HttpData.AddRange(barr);
                }

                if (parser.NetworkReceivedString.Contains("\r\n"))
                {
                    parser.HttpRequest.Add(parser.NetworkReceivedString);
                    parser.NetworkReceivedString = string.Empty;
                }
                else if (parser.ContentIndex == parser.ContentLen)
                {
                    parser.HttpRequest.Add(Encoding.UTF8.GetString(parser.HttpData.ToArray()).Trim());
                    parser.NetworkReceivedString = string.Empty;

                    HttpRequestArgs args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Unknown);
                    if (parser.HttpRequest[0].Contains("GET"))
                    {
                        args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Get);
                    }
                    if (parser.HttpRequest[0].Contains("POST"))
                    {
                        args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Post);
                    }
                    if (parser.HttpRequest[0].Contains("PUT"))
                    {
                        args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Put);
                    }
                    if (parser.HttpRequest[0].Contains("DELETE"))
                    {
                        args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Delete);
                    }

                    RequestEvent?.Invoke(this, args);
                    if (!string.IsNullOrEmpty(args.Respond))
                    {
                        Write(Encoding.UTF8.GetBytes(args.Respond), e.LocalEndPoint, e.RemoteEndPoint);
                    }

                    parser.HttpRequest.Clear();
                    parser.ContentLen   = -1;
                    parser.ContentIndex = 0;
                    parser.HttpData.Clear();
                }


                if (parser.ContentLen == -1 && parser.HttpRequest.Count > 0 && parser.HttpRequest[parser.HttpRequest.Count - 1] == "\r\n")
                {
                    foreach (var reqStr in parser.HttpRequest)
                    {
                        if (reqStr.Contains("Content-Length"))
                        {
                            parser.ContentLen = int.Parse(reqStr.Split(' ')[1]);
                            break;
                        }
                    }
                    if (parser.ContentLen == -1)
                    {
                        parser.NetworkReceivedString = string.Empty;

                        HttpRequestArgs args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Unknown);
                        if (parser.HttpRequest[0].Contains("GET"))
                        {
                            args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Get);
                        }
                        if (parser.HttpRequest[0].Contains("POST"))
                        {
                            args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Post);
                        }
                        if (parser.HttpRequest[0].Contains("PUT"))
                        {
                            args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Put);
                        }
                        if (parser.HttpRequest[0].Contains("DELETE"))
                        {
                            args = new HttpRequestArgs(parser.HttpRequest.ToArray(), HttpRequestMethod.Delete);
                        }

                        RequestEvent?.Invoke(this, args);
                        if (!string.IsNullOrEmpty(args.Respond))
                        {
                            Write(Encoding.UTF8.GetBytes(args.Respond), e.LocalEndPoint, e.RemoteEndPoint);
                        }

                        parser.HttpRequest.Clear();
                        parser.ContentLen   = -1;
                        parser.ContentIndex = 0;
                        parser.HttpData.Clear();
                    }
                }
            }
        }
Exemple #19
0
 protected abstract void ProcessByteInternal(NetworkDataEventArgs e);
        private void ParseHandshake(NetworkDataEventArgs e)
        {
            foreach (byte b in e.Data)
            {
                _parser.NetworkReceivedString += Encoding.UTF8.GetString(new[] { b });

                if (_parser.NetworkReceivedString.Contains("\r\n"))
                {
                    _parser.HttpRequest.Add(_parser.NetworkReceivedString);
                    _parser.NetworkReceivedString = string.Empty;
                }

                if (_parser.HttpRequest.Count > 0 && _parser.HttpRequest[_parser.HttpRequest.Count - 1] == "\r\n")
                {
                    _parser.NetworkReceivedString = string.Empty;

                    try
                    {
                        bool containsSwitch = false;
                        foreach (string s in _parser.HttpRequest)
                        {
                            if (s == "HTTP/1.1 101 Switching Protocols\r\n")
                            {
                                containsSwitch = true;
                                break;
                            }
                        }

                        bool containsUpgrade = false;
                        foreach (string s in _parser.HttpRequest)
                        {
                            if (s == "Upgrade: websocket\r\n")
                            {
                                containsUpgrade = true;
                                break;
                            }
                        }

                        if (containsSwitch && containsUpgrade)
                        {
                            string key = string.Empty;
                            foreach (string s in _parser.HttpRequest)
                            {
                                if (s.Contains("Sec-WebSocket-Accept"))
                                {
                                    var strings = s.Split(new[] { ": ", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                                    key = strings[1];
                                }
                            }

                            if (key != string.Empty)
                            {
                                var acceptKey = AcceptKeyGenerator.AcceptKey(_parser.SentKey);

                                if (key == acceptKey)
                                {
                                    _parser.FirstConnected  = false;
                                    _parser.IsFirstDataByte = true;

                                    HandshakeEvent?.Invoke(this, new ConnectionEventArgs(e.LocalEndPoint, e.RemoteEndPoint));
                                    return;
                                }
                            }
                            OnErrorEvent(new HandshakeException("Wrong Accept"));
                            Stop();
                            return;
                        }

                        OnErrorEvent(new HandshakeException("Respond format error"));
                        Stop();
                    }
                    catch (Exception ex)
                    {
                        OnErrorEvent(new HandshakeException($"Internal error", ex));
                        Stop();
                    }
                }
            }
        }
        public void WebSocketClient_PollFailed_Test()
        {
            var c = new WebSocketClient(String.Empty);

            c.ConnectedEvent    += C_ConnectedEvent;
            c.DisconnectedEvent += C_DisconnectedEvent;
            c.HandshakeEvent    += C_HandshakeEvent;
            c.ErrorEvent        += C_ErrorEvent;

            var clientsCount = 1;
            var ipep         = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4447);
            var epList       = new List <TcpServerLocalEndpoint>
            {
                new TcpServerLocalEndpoint(ipep, clientsCount)
            };

            var s = new TcpServer();

            s.ConnectedEvent    += S_ConnectedEvent;
            s.DisconnectedEvent += S_DisconnectedEvent;
            s.DataReceivedEvent += tcpS_DataReceivedEvent;
            s.Start(epList);

            _serverConnectionEventArgs     = null;
            _clientConnectionEventArgs     = null;
            _serverHandshakeEventArgs      = null;
            _clientHandshakeEventArgs      = null;
            _tcpServerNetworkDataEventArgs = null;
            _serverDisconnectionEventArgs  = null;
            _clietErrorEventArgs           = null;
            c.Start(ipep);
            var startTime = DateTime.Now;

            while (_serverConnectionEventArgs == null || _clientConnectionEventArgs == null)
            {
                var delta = DateTime.Now - startTime;
                if (delta.TotalSeconds > 5)
                {
                    Assert.Fail();
                }
                Thread.Sleep(1);
            }

            startTime = DateTime.Now;
            while (_tcpServerNetworkDataEventArgs == null)
            {
                var delta = DateTime.Now - startTime;
                if (delta.TotalSeconds > 5)
                {
                    Assert.Fail();
                }
                Thread.Sleep(1);
            }

            var str    = Encoding.UTF8.GetString(_tcpServerNetworkDataEventArgs.Data);
            var strarr = str.Split('\r', '\n');

            Assert.IsTrue(strarr[6].Contains("Sec-WebSocket-Key:"));
            var key = strarr[6].Split(':')[1].Trim();

            var retStr = "HTTP/1.1 101 Switching Protocols\r\n";

            retStr += "Upgrade: websocket\r\n";
            retStr += "Connection: Upgrade\r\n";
            retStr += $"Sec-WebSocket-Accept: {AcceptKeyGenerator.AcceptKey(key)}\r\n\r\n";

            s.Write(Encoding.UTF8.GetBytes(retStr), _tcpServerNetworkDataEventArgs.LocalEndPoint, _tcpServerNetworkDataEventArgs.RemoteEndPoint);

            _clientHandshakeEventArgs = null;
            startTime = DateTime.Now;
            while (_clientHandshakeEventArgs == null)
            {
                var delta = DateTime.Now - startTime;
                if (delta.TotalSeconds > 5)
                {
                    Assert.Fail();
                }
                Thread.Sleep(1);
            }

            _tcpServerNetworkDataEventArgs = null;
            startTime = DateTime.Now;
            while (_tcpServerNetworkDataEventArgs == null)
            {
                var delta = DateTime.Now - startTime;
                if (delta.TotalSeconds > 5)
                {
                    Assert.Fail();
                }
                Thread.Sleep(1);
            }
            Assert.AreEqual(0x89, _tcpServerNetworkDataEventArgs.Data[0]);
            Assert.AreEqual(0x00, _tcpServerNetworkDataEventArgs.Data[1]);

            _serverDisconnectionEventArgs = null;
            startTime = DateTime.Now;
            while (_serverDisconnectionEventArgs == null)
            {
                var delta = DateTime.Now - startTime;
                if (delta.TotalSeconds > 10)
                {
                    Assert.Fail();
                }
                Thread.Sleep(1);
            }

            c.Dispose();
            s.Dispose();
        }
 protected override void ProcessByteInternal(NetworkDataEventArgs e)
 {
     OnDataReceivedEvent(e.Data, e.LocalEndPoint, e.RemoteEndPoint);
 }
 private void Sender_SendDataTraceEvent1(object sender, NetworkDataEventArgs e)
 {
     throw new NotImplementedException();
 }
        public void WebSocketClient_HandShake_Fail_Accept_Test()
        {
            var c = new WebSocketClient(String.Empty);

            c.ConnectedEvent    += C_ConnectedEvent;
            c.DisconnectedEvent += C_DisconnectedEvent;
            c.HandshakeEvent    += C_HandshakeEvent;
            c.ErrorEvent        += C_ErrorEvent;

            var clientsCount = 1;
            var ipep         = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4447);
            var epList       = new List <TcpServerLocalEndpoint>
            {
                new TcpServerLocalEndpoint(ipep, clientsCount)
            };

            var s = new TcpServer();

            s.ConnectedEvent    += S_ConnectedEvent;
            s.DisconnectedEvent += S_DisconnectedEvent;
            s.DataReceivedEvent += tcpS_DataReceivedEvent;
            s.Start(epList);

            _serverConnectionEventArgs     = null;
            _clientConnectionEventArgs     = null;
            _serverHandshakeEventArgs      = null;
            _clientHandshakeEventArgs      = null;
            _tcpServerNetworkDataEventArgs = null;
            _clietErrorEventArgs           = null;
            c.Start(ipep);
            var startTime = DateTime.Now;

            while (_serverConnectionEventArgs == null || _clientConnectionEventArgs == null)
            {
                var delta = DateTime.Now - startTime;
                if (delta.TotalSeconds > 5)
                {
                    Assert.Fail();
                }
                Thread.Sleep(1);
            }

            startTime = DateTime.Now;
            while (_tcpServerNetworkDataEventArgs == null)
            {
                var delta = DateTime.Now - startTime;
                if (delta.TotalSeconds > 5)
                {
                    Assert.Fail();
                }
                Thread.Sleep(1);
            }

            var str    = Encoding.UTF8.GetString(_tcpServerNetworkDataEventArgs.Data);
            var strarr = str.Split('\r', '\n');

            Assert.AreEqual("GET  HTTP/1.1", strarr[0]);
            Assert.AreEqual("Upgrade: websocket", strarr[2]);
            Assert.AreEqual("Connection: Upgrade", strarr[4]);
            Assert.IsTrue(strarr[6].Contains("Sec-WebSocket-Key:"));
            Assert.AreEqual("Sec-WebSocket-Version: 13", strarr[8]);

            Assert.IsNull(_clietErrorEventArgs);

            var retStr = "HTTP/1.1 101 Switching Protocols\r\n";

            retStr += "Upgrade: websocket\r\n";
            retStr += "Connection: Upgrade\r\n";
            retStr += $"Sec-WebSocket-Accept: 123\r\n\r\n";

            s.Write(Encoding.UTF8.GetBytes(retStr), _tcpServerNetworkDataEventArgs.LocalEndPoint, _tcpServerNetworkDataEventArgs.RemoteEndPoint);
            startTime = DateTime.Now;
            while (_clietErrorEventArgs == null)
            {
                var delta = DateTime.Now - startTime;
                if (delta.TotalSeconds > 5)
                {
                    Assert.Fail();
                }
                Thread.Sleep(1);
            }
            Assert.AreEqual("Wrong Accept", _clietErrorEventArgs.GetException().Message);

            c.Dispose();
            s.Dispose();
        }
Exemple #25
0
 void ClientDataSent(object sender, NetworkDataEventArgs e)
 {
     if (this.DataSent != null) this.DataSent(sender, e);
 }
 private void tcpS_DataReceivedEvent(object sender, NetworkDataEventArgs e)
 {
     _tcpServerNetworkDataEventArgs = e;
 }
Exemple #27
0
 private void DataReceivedHandler(object sender, NetworkDataEventArgs e)
 {
     if (DataReceived != null) DataReceived(sender, e);
     Thread thread = new Thread(new ParameterizedThreadStart(StartProcessingData));
     thread.IsBackground = true;
     object[] objs = new object[2] { e.Data, sender };
     thread.Start(objs);
 }