public void SetRawValue_ManagedValuesAreAppendedBeforeExtraItems()
        {
            var connectionHeader = new ConnectionHeader
            {
                RawValue = "a,b"
            };

            Assert.False(connectionHeader.Close);
            Assert.False(connectionHeader.KeepAlive);

            connectionHeader.Close = true;
            Assert.Equal("close,a,b", connectionHeader.RawValue);

            connectionHeader.KeepAlive = true;
            Assert.Equal("close,keep-alive,a,b", connectionHeader.RawValue);

            connectionHeader.Close = false;
            Assert.Equal("keep-alive,a,b", connectionHeader.RawValue);

            connectionHeader.Close = true;
            Assert.Equal("close,keep-alive,a,b", connectionHeader.RawValue);

            connectionHeader.KeepAlive = false;
            Assert.Equal("close,a,b", connectionHeader.RawValue);

            connectionHeader.Close = false;
            Assert.Equal("a,b", connectionHeader.RawValue);
        }
        private void ProcessMessage(SystemPacket systemPacket)
        {
            if (systemPacket.Message.GetType() == typeof(MsgOpDisconnectResponse))
            {
            }

            ConnectionHeader ConHeader = systemPacket.Header as ConnectionHeader;

            if (ConHeader != null)
            {
                lock (OperationalSockets)
                {
                    if (systemPacket.OpSocket != null)
                    {
                        Header header = ConHeader.DeserializeHeader(systemPacket.OpSocket);
                        if (header == null)
                        {
                            return;
                        }

                        systemPacket.OpSocket.onReceiveMessage(systemPacket.Message, header);
                    }
                    else
                    {
                    }
                }
            }
            else
            {
                systemPacket.Message.ProcessPayload(Client, null);
            }
        }
Example #3
0
        /// <summary>
        /// Reads Connection Data from a ROM
        /// </summary>
        /// <param name="reader">BinaryReader object to read from</param>
        /// <param name="connectionOffset">Offset of connection data in ROM</param>
        /// <returns>ConnectionHeader object containing all connections of a Map</returns>
        private static ConnectionHeader ConnectionsFromReader(BinaryReader reader, uint connectionOffset)
        {
            ConnectionHeader connections = new ConnectionHeader();

            if (connectionOffset != 0)
            {
                reader.BaseStream.Seek(connectionOffset & 0x1FFFFFF, SeekOrigin.Begin);

                uint connectionCount = reader.ReadUInt32();
                reader.BaseStream.Seek(reader.ReadUInt32() & 0x1FFFFFF, SeekOrigin.Begin);

                for (int i = 0; i < connectionCount; ++i)
                {
                    connections.Connections.Add(new Connection()
                    {
                        Direction    = (Connection.ConnectionDirection)reader.ReadUInt32(),
                        Displacement = reader.ReadInt32(),
                        Bank         = reader.ReadByte(),
                        Map          = reader.ReadByte(),
                        FieldA       = reader.ReadByte(),
                        FieldB       = reader.ReadByte()
                    });
                }
            }
            return(connections);
        }
            public void Must_parse_correctly(object[] parameters)
            {
                var headerValue = (string)parameters[0];
                IEnumerable <string>           connectionTokens = parameters.Where((arg, i) => i > 0).Cast <string>();
                IEnumerable <ConnectionHeader> headers          = ConnectionHeader.ParseMany(headerValue);

                Assert.That(headers.Select(arg => arg.ConnectionToken), Is.EquivalentTo(connectionTokens));
            }
        public void SettingKeepAliveToFalsePreservesClose()
        {
            var connectionHeader = new ConnectionHeader
            {
                RawValue = " keep-alive , close "
            };

            connectionHeader.KeepAlive = false;
            Assert.Equal(" close ", connectionHeader.RawValue);
        }
        public void SetRawValue_WithDuplicatedCloseValues() // This test case is more a side effect result of the global expectation which is to always preserve the raw value set
        {
            var connectionHeader = new ConnectionHeader();

            connectionHeader.RawValue = "close , dummy , close, Close , cLOse";

            Assert.True(connectionHeader.Close);

            Assert.Equal("close , dummy , close, Close , cLOse", connectionHeader.RawValue);
        }
        public void SetRawValue_Null()
        {
            var connectionHeader = new ConnectionHeader
            {
                RawValue = null
            };

            Assert.False(connectionHeader.Close);
            Assert.False(connectionHeader.KeepAlive);

            Assert.Null(connectionHeader.RawValue);
        }
        public void SetRawValue_WithExtraItemsAsDelimitedString(string rawValue, bool expectedClose, bool expectedKeepAlive)
        {
            var connectionHeader = new ConnectionHeader
            {
                RawValue = rawValue
            };

            Assert.Equal(expectedClose, connectionHeader.Close);
            Assert.Equal(expectedKeepAlive, connectionHeader.KeepAlive);

            Assert.Equal(rawValue, connectionHeader.RawValue);
        }
        public void SetRawValue_ManagedValuesAreDetected_And_RawValueIsPreserved(string rawValue, bool expectedClose, bool expectedKeepAlive)
        {
            var connectionHeader = new ConnectionHeader
            {
                RawValue = rawValue,
            };

            Assert.Equal(expectedClose, connectionHeader.Close);
            Assert.Equal(expectedKeepAlive, connectionHeader.KeepAlive);

            Assert.Equal(rawValue, connectionHeader.RawValue);
        }
        public void SetRawValue_Empty()
        {
            var connectionHeader = new ConnectionHeader
            {
                RawValue = ""
            };

            Assert.False(connectionHeader.Close);
            Assert.False(connectionHeader.KeepAlive);

            Assert.Equal("", connectionHeader.RawValue);
        }
        public void Close_SetsOrUnsetRawValue()
        {
            var connectionHeader = new ConnectionHeader();

            connectionHeader.Close = true;
            Assert.Equal("close", connectionHeader.RawValue);

            connectionHeader.Close = false;
            Assert.Null(connectionHeader.RawValue);

            connectionHeader.Close = true;
            connectionHeader.Close = true;
            Assert.Equal("close", connectionHeader.RawValue);
        }
        public void KeepAlive_SetsOrUnsetRawValue()
        {
            var connectionHeader = new ConnectionHeader();

            connectionHeader.KeepAlive = true;
            Assert.Equal("keep-alive", connectionHeader.RawValue);

            connectionHeader.KeepAlive = false;
            Assert.Null(connectionHeader.RawValue);

            connectionHeader.KeepAlive = true;
            connectionHeader.KeepAlive = true;
            Assert.Equal("keep-alive", connectionHeader.RawValue);
        }
Example #13
0
        public byte[] GetBytes()
        {
            byte[] conHeader = ConnectionHeader.GetBytes();
            byte[] msg       = Message.GetBytes();

            Header.Size = (short)(conHeader.Length + msg.Length + 6);
            byte[] header = Header.GetBytes();

            byte[] buffer = new byte[header.Length + conHeader.Length + msg.Length];

            Array.Copy(header, 0, buffer, 0, header.Length);
            Array.Copy(conHeader, 0, buffer, header.Length, conHeader.Length);
            Array.Copy(msg, 0, buffer, header.Length + conHeader.Length, msg.Length);

            return(buffer);
        }
        public void RawValue_IsPreservedWhenManagedValuesAreReverted(string headerValue)
        {
            var connectionHeader = new ConnectionHeader
            {
                RawValue = headerValue
            };

            Assert.Equal(headerValue, connectionHeader.RawValue);

            connectionHeader.Close     = !connectionHeader.Close;
            connectionHeader.Close     = !connectionHeader.Close;
            connectionHeader.KeepAlive = !connectionHeader.KeepAlive;
            connectionHeader.KeepAlive = !connectionHeader.KeepAlive;

            Assert.Equal(headerValue, connectionHeader.RawValue);
        }
        public void WhenRawValueContainsOnlyManagedValues_Then_RemovingManagedValuesSetsRawValueToNull()
        {
            var connectionHeader = new ConnectionHeader
            {
                RawValue = " keep-alive, close "
            };

            Assert.True(connectionHeader.Close);
            Assert.True(connectionHeader.KeepAlive);

            connectionHeader.Close = false;

            Assert.Equal(" keep-alive", connectionHeader.RawValue);

            connectionHeader.KeepAlive = false;

            Assert.Null(connectionHeader.RawValue);
        }
        public void SetRawValue_WithDuplicatedKeepAliveValues() // This test case is more a side effect result of the global expectation which is to always preserve the raw value set
        {
            var connectionHeader = new ConnectionHeader();

            connectionHeader.RawValue = "abc, keep-alive  , Keep-Alive , dummy , keep-alive, kEEp-alive , some, keep-Alive, keep-alive  ";

            Assert.True(connectionHeader.KeepAlive);

            Assert.Equal("abc, keep-alive  , Keep-Alive , dummy , keep-alive, kEEp-alive , some, keep-Alive, keep-alive  ", connectionHeader.RawValue);

            connectionHeader.KeepAlive = false;

            Assert.Equal("abc, Keep-Alive , dummy , keep-alive, kEEp-alive , some, keep-Alive, keep-alive  ", connectionHeader.RawValue);

            connectionHeader.KeepAlive = true;

            Assert.Equal("abc, keep-alive  , Keep-Alive , dummy , keep-alive, kEEp-alive , some, keep-Alive, keep-alive  ", connectionHeader.RawValue);
        }
        public void SetRawValue_AlwaysResetManagedValues()
        {
            var connectionHeader = new ConnectionHeader();

            var header = "dummy , keep-alive";

            connectionHeader.RawValue = header;
            Assert.True(connectionHeader.KeepAlive);
            Assert.False(connectionHeader.Close);
            Assert.Equal(header, connectionHeader.RawValue);

            header = "abc, any ,lose, dummy 1, clos";
            connectionHeader.RawValue = header;
            Assert.False(connectionHeader.KeepAlive);
            Assert.False(connectionHeader.Close);
            Assert.Equal(header, connectionHeader.RawValue);

            header = "close, dummy , keep-alive";
            connectionHeader.RawValue = "close, dummy , keep-alive";
            Assert.True(connectionHeader.KeepAlive);
            Assert.True(connectionHeader.Close);
            Assert.Equal(header, connectionHeader.RawValue);

            header = "close, dummy , keep not alive";
            connectionHeader.RawValue = header;
            Assert.False(connectionHeader.KeepAlive);
            Assert.True(connectionHeader.Close);
            Assert.Equal(header, connectionHeader.RawValue);

            header = "close, dummy , keep-alive";
            connectionHeader.RawValue = header;
            Assert.True(connectionHeader.KeepAlive);
            Assert.True(connectionHeader.Close);
            Assert.Equal(header, connectionHeader.RawValue);

            header = null;
            connectionHeader.RawValue = header;
            Assert.False(connectionHeader.KeepAlive);
            Assert.False(connectionHeader.Close);
            Assert.Equal(header, connectionHeader.RawValue);
        }
        public void SetRawValue_WhenManagedValuesAreInRawValue_Then_RevertingManagedValuesRestoreOriginalRawValue()
        {
            var connectionHeader = new ConnectionHeader
            {
                RawValue = " A     ,  bbb , close , cDe, FFFF ,gG , keep-alive",
            };

            Assert.Equal(" A     ,  bbb , close , cDe, FFFF ,gG , keep-alive", connectionHeader.RawValue);

            connectionHeader.Close = false;
            Assert.Equal(" A     ,  bbb , cDe, FFFF ,gG , keep-alive", connectionHeader.RawValue);

            connectionHeader.KeepAlive = false;
            Assert.Equal(" A     ,  bbb , cDe, FFFF ,gG ", connectionHeader.RawValue);

            connectionHeader.KeepAlive = true;
            Assert.Equal(" A     ,  bbb , cDe, FFFF ,gG , keep-alive", connectionHeader.RawValue);

            connectionHeader.Close = true;
            Assert.Equal(" A     ,  bbb , close , cDe, FFFF ,gG , keep-alive", connectionHeader.RawValue);
        }
Example #19
0
        private Task <bool> SendHello(RegionType type)
        {
            var connHeader = new ConnectionHeader
            {
                UserInfo = new UserInformation
                {
                    EffectiveUser = EffectiveUser
                },
                ServiceName = type.ToString()
            };
            var data   = connHeader.ToByteArray();
            var header = "HBas\x00\x50".ToUtf8Bytes(); // \x50 = Simple Auth.
            var buf    = new byte[header.Length + 4 + data.Length];

            header.CopyTo(buf, 0);
            var dataLenBig = EndianBitConverter.BigEndian.GetBytes((uint)data.Length);

            dataLenBig.CopyTo(buf, 6);
            data.CopyTo(buf, header.Length + 4);
            return(Write(buf, new CancellationToken()));
        }
Example #20
0
        private ConnectionHeader ReadConnectionHeader(BinaryReader reader)
        {
            var result = new ConnectionHeader();

            // Length of protocol string
            byte protocolStringLength = reader.ReadByte();

            // Protocol
            string protocol = new string(reader.ReadChars(protocolStringLength));

            // Reserved bytes
            result.ReservedBytes       = reader.ReadBytes(8);
            result.SupportedExtensions = ProtocolExtensions.DetermineSupportedProcotolExtensions(result.ReservedBytes);

            // Info hash
            result.InfoHash = new Sha1Hash(reader.ReadBytes(20));

            // Peer ID
            result.PeerId = new PeerId(reader.ReadBytes(20));

            return(result);
        }
Example #21
0
        private static string MapConnectionsToString(ConnectionHeader connectionHeader, string baseSymbol)
        {
            StringBuilder b = new StringBuilder();

            b.Append("@ Section: MapConnections "); b.Append(Environment.NewLine);
            b.Append(".align 2"); b.Append(Environment.NewLine);
            b.Append(".global mapconnection_header_"); b.Append(baseSymbol); b.Append(Environment.NewLine);
            b.Append("mapconnection_header_"); b.Append(baseSymbol); b.Append(":"); b.Append(Environment.NewLine);
            b.Append("\t.word "); b.Append(connectionHeader.Connections.Count.ToString()); b.Append(Environment.NewLine);
            if (connectionHeader.Connections.Count > 0)
            {
                b.Append("\t.word mapconnections_"); b.Append(baseSymbol); b.Append(Environment.NewLine);
            }
            else
            {
                b.Append("\t.word 0"); b.Append(Environment.NewLine);
            }
            b.Append(Environment.NewLine);

            if (connectionHeader.Connections.Count > 0)
            {
                b.Append(".global mapconnections_"); b.Append(baseSymbol); b.Append(Environment.NewLine);
                b.Append(".align 2"); b.Append(Environment.NewLine);
                b.Append("mapconnections_"); b.Append(baseSymbol); b.Append(":"); b.Append(Environment.NewLine);
                foreach (Connection connection in connectionHeader.Connections)
                {
                    b.Append("@//new structure"); b.Append(Environment.NewLine);
                    b.Append("\t.word "); b.Append(((int)connection.Direction).ToString()); b.Append(Environment.NewLine);
                    b.Append("\t.word "); b.Append(connection.Displacement.ToString()); b.Append(Environment.NewLine);
                    b.Append("\t.byte "); b.Append(connection.Bank.ToString()); b.Append(Environment.NewLine);
                    b.Append("\t.byte "); b.Append(connection.Map.ToString()); b.Append(Environment.NewLine);
                    b.Append("\t.byte "); b.Append(connection.FieldA.ToString()); b.Append(Environment.NewLine);
                    b.Append("\t.byte "); b.Append(connection.FieldB.ToString()); b.Append(Environment.NewLine);
                }
            }

            return(b.ToString());
        }
        internal async Task OpenConnectionAsync()
        {
            if (_config.EventBusUrl == null)
            {
                // nothing to do
                return;
            }
            if (_webSocket.State == WebSocketState.Open)
            {
                // nothing to do
                return;
            }
            if (
                (_webSocket.State != WebSocketState.Closed) &&
                (_webSocket.State != WebSocketState.None)
                )
            {
                // websocket is in a transitional state; let the timer try to connect later
                _logger.LogDebug("Cannot open WebSocket in current state: {0}", _webSocket.State);
                return;
            }
            var header = new ConnectionHeader {
                Host   = new Uri(_config.EventBusUrl).Host,
                ApiKey = _config.GetEventBusApiKey(),
                Id     = _config.AppInstanceId
            };
            var headerBase64Json = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(header)));
            var eventBusUri      = new Uri($"{_config.EventBusUrl}?header={headerBase64Json}");

            _logger.LogDebug("Connecting to: {0}", eventBusUri);

            // connect/reconnect to websocket
            try {
                await _webSocket.ConnectAsync(eventBusUri, _disposalTokenSource.Token);
            } catch (Exception e) {
                _logger.LogDebug("Unable to connect WebSocket: {0}", e);
                return;
            }
            _logger.LogDebug("Connected!");
            _ = ReceiveMessageLoopAsync();

            // register app with event bus
            if (_disposalTokenSource.IsCancellationRequested)
            {
                // nothing to do
                return;
            }
            try {
                await SendMessageAndWaitForAcknowledgeAsync(new HelloAction());

                // re-subscribe all enabled subscriptions
                foreach (var subscription in _subscriptions.Values.Where(subscription => subscription.IsEnabled))
                {
                    _ = EnableSubscriptionAsync(subscription);
                }

                // notify event handler on connection state change
                StateChanged?.Invoke(this, new EventBusStateChangedEventArgs(open: true));
            } catch (InvalidOperationException) {
                // this exception occurs when the send operation fails because the socket is closed; nothing to do
            } catch (TimeoutException) {
                // this exception occurs when the ack confirmation takes too long
                await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Reset", CancellationToken.None);
            }
        }
Example #23
0
            public void SendSecondaryAddressofPeer()
            {
                Address secondaryAddress = null;
                Connection.ConnectionHeader header = new ConnectionHeader(ConnectionHeader.GET_SECOND_ADDRESS_RSP);
                header.MySecondaryAddress = enclosingInstance.local_addr_s;

                Message msg = new Message(peer_addr, null, new byte[0]);
                msg.putHeader("ConnectionHeader", header);
                NCacheLog.Error("Connection.SendSecondaryAddress",   "secondaryAddr: " + header.MySecondaryAddress);
                SendInternal(Util.Util.serializeMessage(msg));

            }
 public void Must_not_result_in_header(string headerValue)
 {
     Assert.That(ConnectionHeader.ParseMany(headerValue), Is.Empty);
 }
Example #25
0
 public Address GetSecondaryAddressofPeer()
 {
     Connection.ConnectionHeader header = new ConnectionHeader(ConnectionHeader.GET_SECOND_ADDRESS_REQ);
     Message msg = new Message(peer_addr, null, new byte[0]);
     msg.putHeader("ConnectionHeader", header);
     lock (get_addr_sync)
     {
         SendInternal(Util.Util.serializeMessage(msg));
         Monitor.Wait(get_addr_sync);
     }
     return secondaryAddress;
 }
Example #26
0
 /// <summary>
 /// Sends notification to other node about leaving.
 /// </summary>
 public void SendLeaveNotification()
 {
     leavingGracefully = true;
     ConnectionHeader header = new ConnectionHeader(ConnectionHeader.LEAVE);
     Message leaveMsg = new Message(peer_addr, null, new byte[0]);
     leaveMsg.putHeader("ConnectionHeader", header);
     if (NCacheLog.IsInfoEnabled) NCacheLog.Info("Connection.SendSilentCloseNotification",   "sending leave request");
     try
     {
         byte[] binaryMsg = Util.Util.serializeMessage(leaveMsg);
         SendInternal(binaryMsg);
     }
     catch (Exception e)
     {
         NCacheLog.Error("Connection.SendLeaveNotification",   e.ToString());
     }
 }
Example #27
0
 public bool SendInitializationPhaseRsp(bool initializationPhase)
 {
     self_close = true;
     ConnectionHeader header = new ConnectionHeader(ConnectionHeader.INITIALIZATION_PHASE_RSP);
     header.InitializationPhase = initializationPhase;
     Message closeMsg = new Message(peer_addr, null, new byte[0]);
     closeMsg.putHeader("ConnectionHeader", header);
     if (NCacheLog.IsInfoEnabled) NCacheLog.Info("Connection.SendSilentCloseNotification",   "sending silent close request");
     try
     {
         lock (initializationPhase_mutex)
         {
             byte[] binaryMsg = Util.Util.serializeMessage(closeMsg);
             SendInternal(binaryMsg);
             Monitor.Wait(initializationPhase_mutex);
             return inInitializationPhase;
         }
     }
     catch (Exception e)
     {
         NCacheLog.Error("Connection.SendSilentCloseNotification",   e.ToString());
     }
     return false;
 }
Example #28
0
            /// <summary>
            /// Sends the notification to the peer that connection is being closed silently.
            /// </summary>
            private void SendSilentCloseNotification()
            {
                self_close = true;
                ConnectionHeader header = new ConnectionHeader(ConnectionHeader.CLOSE_SILENT);
                Message closeMsg = new Message(peer_addr, null, new byte[0]);
                closeMsg.putHeader("ConnectionHeader", header);
                if (NCacheLog.IsInfoEnabled) NCacheLog.Info("Connection.SendSilentCloseNotification",   "sending silent close request");
                try
                {
                    byte[] binaryMsg = Util.Util.serializeMessage(closeMsg);

                    SendInternal(binaryMsg);
                }
                catch (Exception e)
                {
                    NCacheLog.Error("Connection.SendSilentCloseNotification",   e.ToString());
                }
                

            }
Example #29
0
        private void dealProxyRequest(object obj)
        {
            try
            {
                TcpClient client = (TcpClient)obj;
                Console.WriteLine(((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
                HTTPRequest request;
                using (BinaryReader breader = new BinaryReader(client.GetStream()))
                {
                    byte[]        b          = new byte[1];
                    string        ht         = "";
                    List <string> rawHeaders = new List <string>();
                    while (client.GetStream().CanRead&& client.GetStream().DataAvailable)
                    {
                        b[0] = breader.ReadByte();
                        ht  += Encoding.ASCII.GetString(b);

                        if (ht.Contains("\r\n"))
                        {
                            rawHeaders.Add(ht);
                            if (ht == "\r\n")
                            {
                                break;
                            }
                            ht = "";
                        }
                    }
                    string sr = "";
                    foreach (string st in rawHeaders)
                    {
                        sr += st;
                    }
                    if (rawHeaders.Count == 0)
                    {
                        client.Dispose();
                        return;
                    }
                    request = SophieHTTP.HTTPResolve.HTTPResolve.ResolveHTTPRequest(Encoding.ASCII.GetBytes(sr));
                    if (request.Method.MethodName == HTTPMethod.CONNECT.MethodName)
                    {
                        request.Url = new Uri("https://" + request.Url.OriginalString + "/");
                        TcpClient remoteServer = new TcpClient();
                        try
                        {
                            remoteServer.Connect(Dns.GetHostEntry(request.Url.Host).AddressList[0], Convert.ToInt32(request.Url.Port));
                            HTTPResponse resp = new HTTPResponse(HTTPVersion.HTTP11, HTTPStatusCode.ConnectionEstablished, new List <HTTPHeader>());
                            if (client.Connected)
                            {
                                client.GetStream().Write(resp.GetRawBytes(), 0, resp.GetRawBytes().Length);
                            }
                            else
                            {
                                client.Dispose();
                                return;
                            }

                            NetworkStream serverStream = remoteServer.GetStream();
                            NetworkStream clientStream = client.GetStream();
                            while (client.Connected)
                            {
                                Thread.Sleep(1);
                                if (serverStream.CanRead && clientStream.CanRead && serverStream.CanWrite && clientStream.CanWrite)
                                {
                                    try
                                    {
                                        if (clientStream.DataAvailable)
                                        {
                                            byte[] buf  = new byte[1024];
                                            int    size = clientStream.Read(buf, 0, 1024);
                                            serverStream.Write(buf, 0, size);
                                        }
                                        if (serverStream.DataAvailable)
                                        {
                                            byte[] buf  = new byte[1024];
                                            int    size = serverStream.Read(buf, 0, 1024);
                                            clientStream.Write(buf, 0, size);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        break;
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                            remoteServer.Dispose();
                            client.Dispose();
                        }
                        catch (SocketException ex)
                        {
                            HTTPResponse resp = new HTTPResponse(HTTPVersion.HTTP11, HTTPStatusCode.BadGateway, new List <HTTPHeader>());
                            resp.Content = Encoding.Unicode.GetBytes(ex.Message);
                            client.GetStream().Write(resp.GetRawBytes(), 0, resp.GetRawBytes().Length);
                            client.Dispose();
                        }
                    }
                    else
                    {
                        if (request.Version == HTTPVersion.HTTP09 || request.Version == HTTPVersion.HTTP10)
                        {
                            if (client.Connected)
                            {
                                HTTPResponse resp = new HTTPResponse(request.Version, HTTPStatusCode.HttpVersionNotSupported, new List <HTTPHeader>());
                                resp.Content = Encoding.UTF8.GetBytes("请升级到支持HTTP1.1的浏览器");
                                resp.AddHeader(new CommonHeader("Content-Type: text/html; charset=utf-8"));
                                client.GetStream().Write(resp.GetRawBytes(), 0, resp.GetRawBytes().Length);
                                return;
                            }
                            else
                            {
                                client.Dispose();
                                return;
                            }
                        }
                        string host;
                        int    port;
                        try
                        {
                            host = request.Url.Host;
                            port = request.Url.Port;
                        }catch (Exception ex)
                        {
                            if (request.FindHeader("Host") != null)
                            {
                                host = (string)request.FindHeader("Host").Value;
                                port = 80;
                            }
                            else
                            {
                                HTTPResponse resp = new HTTPResponse(request.Version, HTTPStatusCode.BadRequest, new List <HTTPHeader>());
                                resp.Content = Encoding.UTF8.GetBytes("错误的请求");
                                resp.AddHeader(new CommonHeader("Content-Type: text/html; charset=utf-8"));
                                client.GetStream().Write(resp.GetRawBytes(), 0, resp.GetRawBytes().Length);
                                return;
                            }
                        }
                        if (request.FindHeader("Connection") == null)
                        {
                            request.AddHeader(new ConnectionHeader("Connection:close"));
                        }
                        if (((ConnectionHeader)request.FindHeader("Connection")).FindValue("close") == null)
                        {
                            ConnectionHeader ch = (ConnectionHeader)request.FindHeader("Connection");
                            ch.Value = new List <string>();
                            ((List <string>)ch.Value).Add("close");
                        }
                        try
                        {
                            IPAddress remoteAddress = Dns.GetHostEntry(host).AddressList[0];
                            TcpClient remoteServer  = new TcpClient(new IPEndPoint(remoteAddress, port));
                            remoteServer.GetStream().Write(request.GetRawBytes(), 0, request.GetRawBytes().Length);
                        }
                        catch (SocketException ex)
                        {
                            HTTPResponse resp = new HTTPResponse(HTTPVersion.HTTP11, HTTPStatusCode.BadGateway, new List <HTTPHeader>());
                            resp.Content = Encoding.Unicode.GetBytes(ex.Message);
                            client.GetStream().Write(resp.GetRawBytes(), 0, resp.GetRawBytes().Length);
                            client.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }