Example #1
0
        private static void CreateClientSocket()
        {
            _serverConfig = _serviceProvider.GetRequiredService <IOptions <ServerConfig> >()?.Value;
            _client       = _serviceProvider.GetRequiredService <IClientSocket>();
            _timers.Start();
            Task.Run(async() => await _client.ConnectAsync(_serverConfig.IpAddress, _serverConfig.Port)
                     .ConfigureAwait(false))
            .ContinueWith(tresult =>
            {
                if (tresult.Status == TaskStatus.Faulted)
                {
                    Console.WriteLine($"connect {_serverConfig.IpAddress}:{_serverConfig.Port} faulted");
                    _needReConnecting = true;
                }
            });
            string line = null;

            while ((line = Console.ReadLine()) != "")
            {
                if (line == "r")
                {
                    Console.WriteLine("Reconnecting...");
                    _client.Disconnect();
                    Task.Run(async() => await _client.ConnectAsync(_serverConfig.IpAddress, _serverConfig.Port))
                    .ContinueWith(tresult =>
                    {
                        if (tresult.Status == TaskStatus.Faulted)
                        {
                            Console.WriteLine($"Connected Faulted.");
                        }
                        else
                        {
                            Console.WriteLine($"IsConnected = {_client.IsConnected}");
                        }
                    });
                }
                else if (line == "exit")
                {
                    _client.Disconnect();
                    break;
                }
                else
                {
                    Console.WriteLine($"{line}  Sending..");
                    _client.SendAsync(line, 3, ErrorMessageCallback).ConfigureAwait(false);
                }
            }
        }
Example #2
0
 private static void _timers_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     if (!_needReConnecting)
     {
         Console.WriteLine("dont need to connect againg.");
         return;
     }
     _needReConnecting = false;
     Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:ThreadState:{Thread.CurrentThread.ThreadState}, Reconnecting to Server.");
     if (_client == null)
     {
         _client = _serviceProvider.GetRequiredService <IClientSocket>();
     }
     if (!_client.IsConnected)
     {
         Task.Run(async() => await _client.ConnectAsync(_serverConfig.IpAddress, _serverConfig.Port))
         .ContinueWith(tresult =>
         {
             if (tresult.Status == TaskStatus.Faulted)
             {
                 _needReConnecting = true;
                 Console.WriteLine($"{Task.CurrentId} status changed to  {_needReConnecting}.");
             }
             else
             {
                 Console.WriteLine("Successfully connected to the Server.");
             }
         });
     }
 }
Example #3
0
        /// <summary>
        /// 连接websocketServer
        /// </summary>
        /// <returns></returns>
        public bool Connect(int timeOut = 10 * 1000)
        {
            _client.ConnectAsync((e) =>
            {
                _client.SendAsync(WSUserToken.RequestHandShark(_url, _serverIP, _serverPort, _subProtocol, _origin));
            });

            var to = timeOut / 10;

            int i = 0;

            while (!_isHandSharked && i < to)
            {
                Thread.Sleep(10);
                i++;
            }

            if (_isHandSharked)
            {
                return(true);
            }

            _client.Disconnect();

            return(false);
        }
Example #4
0
 public bool Connect(string _host, int _port)
 {
     this.Close();
     host     = _host;
     port     = _port;
     m_socket = this.NewSocket();
     m_socket.Reset(host, port);
     m_state = NetAgentState.Connecting;
     return(m_socket.ConnectAsync(OnSocketOpen, OnSocketRecvData, OnSocketClose));
 }
Example #5
0
 public void Connect()
 {
     if (!_client.Connected)
     {
         _client.ConnectAsync((c) =>
         {
             if (c != System.Net.Sockets.SocketError.Success)
             {
                 throw new KernelException("连接到消息服务器失败,Code:" + c.ToString());
             }
         });
     }
 }
        public void ConnectAsync()
        {
            _client.ConnectAsync((e) =>
            {
                log4j.Info("in callback of SocketError, " + e);
                switch (e)
                {
                case SocketError.Success:
                    _client_OnConnected();
                    break;

                default:
                    OnDisconnected?.Invoke("", new SocketException((int)e));
                    break;
                }
            });
        }
Example #7
0
 public void Setup()
 {
     _tcpService.Accepted.SubscribeOn(TaskPoolScheduler.Default)
     .Subscribe
     (
         r => _client.ConnectAsync(_config.IpAddress, _config.Port),
         ex => Console.WriteLine(ex),
         () => Console.WriteLine("Server Start completed")
     );
     _tcpService.Reciever.SubscribeOn(TaskPoolScheduler.Default)
     .Subscribe(
         r => Console.WriteLine($"Receive:{r.Message} from [{r.EndPoint}]"),
         ex => Console.WriteLine(ex),
         () => Console.WriteLine("Socket receiver completed")
         );
     Task.Run(() => _tcpService.StartAsync());
 }
Example #8
0
        /// <summary>
        /// 连接websocketServer
        /// </summary>
        /// <returns></returns>
        public bool Connect(int timeOut = 10 * 1000)
        {
            _client.ConnectAsync((e) =>
            {
                this.RequestHandShark();
            });

            int i = 0;

            while (!_isHandSharked && i < (timeOut / 10))
            {
                Thread.Sleep(10);
                i++;
            }
            if (_isHandSharked)
            {
                return(true);
            }

            return(false);
        }
Example #9
0
 /// <summary>
 /// 连接
 /// </summary>
 /// <param name="callBack"></param>
 public void ConnectAsync(Action <SocketError> callBack = null)
 {
     _clientSocket.ConnectAsync(callBack);
 }
Example #10
0
 public void Connect()
 {
     _client.ConnectAsync().GetAwaiter();
 }
Example #11
0
 /// <summary>
 /// 连接
 /// </summary>
 public void Connect()
 {
     _client.ConnectAsync();
 }
Example #12
0
 public async Task ConnectAsync()
 {
     await _clientSocket.ConnectAsync();
 }
Example #13
0
 public void ConnectAsync()
 {
     _clientSocket.ConnectAsync();
 }
Example #14
0
 public Task ClientConnectAsync()
 {
     return(_clientSocket.ConnectAsync(Const.Ip, Const.Port));
 }
Example #15
0
        /// <summary>
        /// Http2Client
        /// </summary>
        /// <param name="host"></param>
        /// <param name="ip"></param>
        /// <param name="scheme"></param>
        /// <param name="path"></param>
        /// <param name="authority"></param>
        /// <param name="useHttp1Upgrade"></param>
        /// <param name="size"></param>
        /// <param name="timeOut"></param>
        public Http2Client(string host, int ip, string scheme, string path, string authority, bool useHttp1Upgrade = false, int size = 1024, int timeOut = 180 * 1000)
        {
            _path = path;

            _authority = authority;

            var options = SocketOptionBuilder.Instance.SetSocket(Sockets.Model.SAEASocketType.Tcp)
                          .UseStream()
                          .SetIP(host)
                          .SetPort(ip)
                          .SetReadBufferSize(size)
                          .SetWriteBufferSize(size)
                          .SetTimeOut(timeOut)
                          .Build();

            _clientSocket = SocketFactory.CreateClientSocket(options);

            _clientSocket.ConnectAsync().GetAwaiter();

            var config = new ConnectionConfigurationBuilder(false)
                         .UseSettings(Settings.Default)
                         .UseHuffmanStrategy(HuffmanStrategy.IfSmaller)
                         .Build();

            var wrappedStreams = _clientSocket.Socket.CreateStreams();

            if (useHttp1Upgrade)
            {
                var upgrade = new ClientUpgradeRequestBuilder()
                              .SetHttp2Settings(config.Settings)
                              .Build();

                var upgradeReadStream = new UpgradeReadStream(wrappedStreams.ReadableStream);

                var needExplicitStreamClose = true;

                try
                {
                    var upgradeHeader = "OPTIONS / HTTP/1.1\r\n" +
                                        "Host: " + host + "\r\n" +
                                        "Connection: Upgrade, HTTP2-Settings\r\n" +
                                        "Upgrade: h2c\r\n" +
                                        "HTTP2-Settings: " + upgrade.Base64EncodedSettings + "\r\n\r\n";

                    var encodedHeader = Encoding.ASCII.GetBytes(upgradeHeader);

                    wrappedStreams.WriteableStream.WriteAsync(new ArraySegment <byte>(encodedHeader)).GetAwaiter();

                    upgradeReadStream.WaitForHttpHeader().GetAwaiter();

                    var headerBytes = upgradeReadStream.HeaderBytes;

                    upgradeReadStream.ConsumeHttpHeader();

                    var response = Http1Response.ParseFrom(Encoding.ASCII.GetString(headerBytes.Array, headerBytes.Offset, headerBytes.Count - 4));

                    if (response.StatusCode != "101")
                    {
                        throw new Exception("升级失败");
                    }

                    if (!response.Headers.Any(hf => hf.Key == "connection" && hf.Value == "Upgrade") ||
                        !response.Headers.Any(hf => hf.Key == "upgrade" && hf.Value == "h2c"))
                    {
                        throw new Exception("升级失败");
                    }

                    needExplicitStreamClose = false;

                    var conn = new Connection(config, upgradeReadStream, wrappedStreams.WriteableStream, options: new Connection.Options
                    {
                        ClientUpgradeRequest = upgrade,
                    });


                    var upgradeStream = upgrade.UpgradeRequestStream.GetAwaiter().GetResult();

                    upgradeStream.Cancel();

                    _conn = conn;
                }
                finally
                {
                    if (needExplicitStreamClose)
                    {
                        wrappedStreams.WriteableStream.CloseAsync();
                    }
                }
            }
            else
            {
                _conn = new Connection(config, wrappedStreams.ReadableStream, wrappedStreams.WriteableStream, options: new Connection.Options());
            }
        }