internal Connection(AppModel appModel, IChannel channel) { Preconditions.ArgumentNullException(channel != null && appModel != null); //TODO 这里的appModel是被当成Environment用的,只是用到了LocalDevice,应该把AppModel拆成两个东西。 this.appModel = appModel; this.channel = channel; channel.PacketReceived += (Packet packet) => { Message message = Message.FromPacket(packet); if (message != null) { OnMessageReceived(message); } }; channel.ErrorHappened += (type) => { State = ConnectionState.Error; }; _state = ConnectionState.Connecting; sendWorker = new BackgroundWorker { WorkerSupportsCancellation = true }; sendWorker.DoWork += SendWorker_DoWork; //TODO应该在第一次Post东西的时候才启动。 sendWorker.RunWorkerAsync(); timeoutTimer = new System.Timers.Timer(TimeoutInterval); timeoutTimer.Elapsed += OnTimeout; //创建之后即开始记录超时。发送消息重置超时。连接完成之后,收到消息也会重置超时。连接被同意之前,收掉的其他消息不会重置超时。 //不要使用心跳包。如果一个连接长时间不用,就让它关掉。上层如果需要这个connection,会重新创建。 timeoutTimer.Start(); }
internal TcpChannel(TcpClient client) { Preconditions.ArgumentNullException(client != null); this.client = client; if (client.Client.RemoteEndPoint is IPEndPoint) { var iep = client.Client.RemoteEndPoint as IPEndPoint; RemoteIP = iep.Address.ToString(); } //client.Client.ReceiveTimeout = 6000; readWorker = new BackgroundWorker { WorkerSupportsCancellation = true }; readWorker.DoWork += ReadWorker_DoWork; readWorker.RunWorkerAsync(); }