/// <summary> /// 从服务端读取配置 /// </summary> /// <returns></returns> private async Task <ClientModel> ReadConfigFromProvider() { //《c#并发编程经典实例》 9.3 超时后取消 var config = NSmartProxy.Client.Router.ClientConfig; Router.Logger.Debug("Reading Config From Provider.."); TcpClient configClient = new TcpClient(); var delayDispose = Task.Delay(TimeSpan.FromSeconds(600)).ContinueWith(_ => configClient.Dispose()); var connectAsync = configClient.ConnectAsync(config.ProviderAddress, config.ProviderConfigPort); //超时则dispose掉 var comletedTask = await Task.WhenAny(delayDispose, connectAsync); if (!connectAsync.IsCompleted) { throw new Exception("连接超时"); } var configStream = configClient.GetStream(); //请求1 端口数 var requestBytes = new ClientNewAppRequest { ClientId = 0, ClientCount = config.Clients.Count(obj => obj.AppId == 0) //appid为0的则是未分配的 }.ToBytes(); await configStream.WriteAsync(requestBytes, 0, requestBytes.Length); //请求2 分配端口 //var requestBytes byte[] requestBytes2 = new byte[config.Clients.Count * 2]; int i = 0; foreach (var client in config.Clients) { byte[] portBytes = StringUtil.IntTo2Bytes(client.ConsumerPort); requestBytes2[2 * i] = portBytes[0]; requestBytes2[2 * i + 1] = portBytes[1]; i++; } await configStream.WriteAsync(requestBytes2, 0, requestBytes2.Length); //读端口配置 byte[] serverConfig = new byte[256]; int readBytesCount = await configStream.ReadAsync(serverConfig, 0, serverConfig.Length); if (readBytesCount == 0) { Router.Logger.Debug("服务器状态异常,已断开连接"); } return(ClientModel.GetFromBytes(serverConfig, readBytesCount)); }
/// <summary> /// 从服务端读取配置 /// </summary> /// <returns></returns> private async Task <ClientModel> ReadConfigFromProvider() { //《c#并发编程经典实例》 9.3 超时后取消 var config = NSmartProxy.Client.Router.ClientConfig; Router.Logger.Debug("Reading Config From Provider.."); TcpClient configClient = new TcpClient(); var delayDispose = Task.Delay(TimeSpan.FromSeconds(2)).ContinueWith(_ => configClient.Dispose()); var connectAsync = configClient.ConnectAsync(config.ProviderAddress, config.ProviderConfigPort); //超时则dispose掉 var comletedTask = await Task.WhenAny(delayDispose, connectAsync); if (!connectAsync.IsCompleted) { throw new Exception("连接超时"); } var configStream = configClient.GetStream(); var requestBytes = new ClientNewAppRequest { ClientId = 0, ClientCount = config.Clients.Count(obj => obj.AppId == 0) //appid为0的则是未分配的 }.ToBytes(); configStream.Write(new ClientNewAppRequest { ClientId = 0, ClientCount = config.Clients.Count(obj => obj.AppId == 0) //appid为0的则是未分配的 }.ToBytes(), 0, requestBytes.Length); byte[] serverConfig = new byte[256]; int readBytesCount = configStream.Read(serverConfig, 0, serverConfig.Length); if (readBytesCount == 0) { Router.Logger.Debug("服务器状态异常,已断开连接"); } return(ClientModel.GetFromBytes(serverConfig, readBytesCount)); }