public static void Send(IProtocolInfo info) { var messageThread = new Thread(() => { try { // 遍历所有客户端 foreach (var clientPair in StudentDevices) { var studentClient = clientPair.Value; //if (modifyInfoByClient != null) //{ // modifyInfoByClient(clientPair); //} if (studentClient != null) { IPackageInfo package = DefaultPackageDealer.Seal(info); TcpServer.SendAsync(studentClient, package.ToBytes()); } } } catch (Exception ex) { logger.Error(ex); } }); messageThread.Start(); }
/// <summary> /// 处理接收操作 /// 当一个异步接收操作完成时调用此方法 /// </summary> /// <param name="receiveContext">与完成Receive操作关联的SocketAsyncEventArg对象</param> private void ProcessReceive(SocketAsyncEventArgs receiveContext) { if (!IsSocketAlive(receiveContext)) { return; } // BytesTransferred属性提供在可接收或发送数据的异步套接字操作传输的字节数。 // 如果从读取操作返回零,则说明远程端已关闭了连接 if (receiveContext.BytesTransferred > 0) { if (receiveContext.SocketError == SocketError.Success) { try { ITcpClientProxy dataHandler = receiveContext.UserToken as ITcpClientProxy; //bool receiveComplete = dataHandler.ReceiveData(receiveContext); List <IPackageInfo> packages = null; bool receiveComplete = dataHandler.TryReceivePackages(receiveContext, out packages); if (receiveComplete) { // 调用消息接收完毕事件 try { this.OnMessageReceived(receiveContext); } catch (Exception ex) { _logger.Error(ex.StackTrace); } // 返回响应消息 // review: 这里应该用TryReceivePackages返回的集合? IPackageInfo response = dataHandler.ExchangedData as IPackageInfo; if (response != null) { SendReuseAsync(dataHandler, response.ToBytes()); } else if (this.Echo) { SendReuseAsync(dataHandler, dataHandler.LastReceivedBytes); } else { StartReceive(receiveContext); } //string exchnagedData = dataHandler.ExchangedData == null ? "" : dataHandler.ExchangedData.ToString(); ////todo: 消息分段发送 //if (string.IsNullOrEmpty(exchnagedData) && this.Echo) //{ // //dataHandler.Echo(receiveContext); // //Send(dataHandler, dataHandler.LastMessage.Content); // if (packages.Count > 0) // { // Send(dataHandler, packages[0].ToBytes()); // } // //Send(dataHandler, packages[0].ToBytes()); //} //else //{ // //Send(dataHandler, exchnagedData); //} //dataHandler.PrepareOutgoingData(dataHandler.SendContext, exchnagedData); //StartSend(dataHandler.SendContext); } else { // 如果没有读取完,继续接收下一段数据 StartReceive(receiveContext); } } catch (Exception ex) { _logger.Error("Unexpected error:" + ex.StackTrace); Console.WriteLine("Unexpected error:" + ex.StackTrace); } } else { Console.WriteLine("Socket接受时错误, 代号:" + receiveContext.SocketError); _logger.Error("Socket接受时错误, 代号:" + receiveContext.SocketError); this.ProcessError(receiveContext); } } else { // 如果远程端关闭了连接,这里也关闭Socket Console.WriteLine("平板端关闭了连接."); _logger.Error("平板端关闭了连接."); this.ProcessError(receiveContext); } }
public bool Send(ITcpClientProxy target, IPackageInfo content) { return(Send(target, content.ToBytes())); }