/// <summary> /// the method get a message and write to the tcp server this message /// </summary> /// <param name="msg">the msg to write</param> public void Write(string msg) { DataReceivedEventArgs d = new DataReceivedEventArgs(); d.Message = msg; m_tcpServer.Send(this, d); }
/// <summary> /// 线程池任务回调函数 /// </summary> /// <param name="obj">任务参数</param> private void TaskTaskProc(object obj) { if (!(obj is TaskInfo taskInfo)) { return; } // 如果连接已经断开了(可能被踢了) // 它的任务就不做了(根据自己业务需求来, 也许你的任务就是要完成每个连接的所有任务, 每个包都要处理, 不管连接断开与否, 就不要写这个判断, 但是你回发包的时候要判断是否有效连接) if (!_server.IsConnected(taskInfo.Client.ConnId)) { return; } // 在这里处理耗时任务逻辑 switch (taskInfo.Packet.Type) { case PacketType.Time: { // 模拟耗时操作 Thread.Sleep(6000); // 组织packet为一个json var json = JsonConvert.SerializeObject(new Packet { Type = PacketType.Time, Data = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), }); // json转字节数组 var bytes = Encoding.UTF8.GetBytes(json); // 先发包头 if (!SendPacketHeader(_server, taskInfo.Client.ConnId, bytes.Length)) { // 发送失败断开连接 _server.Disconnect(taskInfo.Client.ConnId); break; } // 再发实际数据 if (!_server.Send(taskInfo.Client.ConnId, bytes, bytes.Length)) { _server.Disconnect(taskInfo.Client.ConnId); } // 至此完成当前任务 break; } } }
public void Send(ulong id, IMessage message) { m_server.Send(id, ProtocolBuffConvert.Serialize(message)); }