/// <summary> /// 心跳包发送线程 /// </summary> public static void socketSend() { int i = 0; while (true) { Thread.Sleep(2000); try { Console.WriteLine("发送心跳包"); List <DownloadFile> files = new List <DownloadFile>(); foreach (TorrentManager manager in torrents) { DownloadFile downloadFile = new DownloadFile(manager.State.ToString(), manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name, manager.Monitor.DownloadSpeed / 1024.0, manager.Monitor.UploadSpeed / 1024.0, manager.Progress); files.Add(downloadFile); } PCKeepAlivePacket loginReq = new PCKeepAlivePacket { keepAliveType = PCKeepAlivePacket.KeepAliveType.SUCCESS, data = JsonConvert.SerializeObject(files), }; MemoryStream ms = new MemoryStream(); Serializer.Serialize(ms, loginReq); byte[] data = ms.ToArray(); byte[] Buff = NetTcpBase.PackMessage((int)ENetworkMessage.PC_KEEP_ALIVE, LittleEndian.GetLittleEndianBytes(1), data); bw.Write(Buff, 0, Buff.Length); bw.Flush(); } catch (SocketException) { Thread.CurrentThread.Abort(); //throw ex; } } }
/// <summary> /// 连接中转服务器 /// </summary> private static void connectServer() { byte[] buf = new byte[1024]; string input; IPAddress local = IPAddress.Parse("127.0.0.1"); IPEndPoint iep = new IPEndPoint(local, 13333); try { tcpClient = new TcpClient(); tcpClient.Connect("127.0.0.1", 13333); Console.WriteLine("开始连接服务器"); ns = tcpClient.GetStream(); } catch (SocketException) { Console.WriteLine("无法连接到服务器!"); return; } bw = new BinaryWriter(ns); br = new BinaryReader(ns); //启动心跳发送线程 Thread sendEcho = new Thread(new ThreadStart(socketSend)); sendEcho.Start(); sendEcho.IsBackground = true; //启动消息接收线程 Thread receiveThread = new Thread(new ThreadStart(socketReceive)); receiveThread.Start(); receiveThread.IsBackground = true; //构造初始化请求报文 P2PInitReq initReq = new P2PInitReq { msgFrom = P2PInitReq.MsgFrom.PC, userName = user, }; MemoryStream ms = new MemoryStream(); Serializer.Serialize(ms, initReq); byte[] data = ms.ToArray(); initBuff = NetTcpBase.PackMessage((int)ENetworkMessage.P2P_INIT_REQ, LittleEndian.GetLittleEndianBytes(1), data); Thread.Sleep(5000); init(bw, br, initBuff); }