private void JieShou() { try { while (Client != null) { net = Client.GetStream(); if (net.CanWrite == false) { Client = null; return; } if (net.DataAvailable == true) { byte[] tmp = new byte[1024]; MemoryStream memory = new MemoryStream(); int len = 1; while (len != 0) { if (net.DataAvailable == false) { break; } len = net.Read(tmp, 0, tmp.Length); memory.Write(tmp, 0, len); } if (memory.ToArray().Length != 4) { NetMsg msg = (NetMsg)XuLie.ByteToObj(memory.ToArray()); textBox1.Text += msg.Fip.ToString() + "说: " + msg.msg + "\r\n"; } } Thread.Sleep(200); } } catch (Exception err) { MessageBox.Show(err.Message); lock (textBox1) { //textBox1.Text = err.Message; } } }
private void ThSub() { try { while (Client != null) { NetworkStream Net = Client.GetStream(); if (Net.DataAvailable == true) //有数据。 { byte[] tmp = new byte[1024]; if (Net.CanRead == true) { MemoryStream memory = new MemoryStream(); memory.Position = 0; int len = 1; while (len != 0) { if (Net.DataAvailable == false) { break; } len = Net.Read(tmp, 0, tmp.Length); memory.Write(tmp, 0, len); } log.LogWriter("接收完毕"); NetMsg msg = (NetMsg)XuLie.ByteToObj(memory.ToArray()); log.LogWriter("序列化完毕"); TcpClient tcpclient = new TcpClient(); log.LogWriter("建立TCP对象"); if (msg.Fip != null) //非心跳包。 { try { tcpclient.Connect(msg.JieIP, msg.port); NetworkStream SubNet = tcpclient.GetStream(); byte[] Tmp = XuLie.ObjToByte(msg); SubNet.Write(Tmp, 0, Tmp.Length); } catch (SocketException) { msg.msg = "对方不在线"; byte[] Tmp = XuLie.ObjToByte(msg); Net.Write(Tmp, 0, Tmp.Length); } } else { if (msg.msg == "QUIT") { Arr.Remove(Client); return; } } tcpclient.Close(); GC.Collect(); } } else //没有数据。 { } Thread.Sleep(1000); } } catch { Arr.Remove(Client); th.Abort(); } }