private void StartListen(object obj) { Socket socketWatch = obj as Socket; while (true) { try { thrRecv = new Thread(ReceiveMessage); thrRecv.Start(); //等待客户端的连接,并且创建一个用于通信的Socket socketSend = socketWatch.Accept(); //获取远程主机的ip地址和端口号 string strIp = socketSend.RemoteEndPoint.ToString(); dicSocket.Add(strIp, socketSend);//把连接服务器的主机上的IP和Socket保存起来 string strMsg = "远程主机:" + socketSend.RemoteEndPoint + "连接成功"; Invoke(zhangfalixian, "."); string[] sf = message.Split(','); message = ""; Zhuanfa jj = new Zhuanfa(int.Parse(sf[0]), int.Parse(sf[1]), strIp, socketSend, sf[3].ToString(), sf[2].ToString()); arrlist.Add(jj); this.dataGridView1.Invoke(setCmbCallBack, arrlist); //使用回调 richTextBox1.Invoke(setCallBack, strMsg); //定义接收客户端消息的线程 threadReceive = new Thread(new ParameterizedThreadStart(Receive)); threadReceive.IsBackground = true; threadReceive.Start(socketSend); } catch (Exception) { Invoke(zhangfalixian, "."); } } }
private void Receive(object obj) { Socket socketSend = obj as Socket; while (true) { try { //客户端连接成功后,服务器接收客户端发送的消息 byte[] buffer = new byte[2048 * 10000]; //实际接收到的有效字节数 int count = socketSend.Receive(buffer); if (count == 0) //count 表示客户端关闭,要退出循环 { break; } else { if (buffer[0] == 1) { string str = Encoding.Default.GetString(buffer, 0, count); strReceiveMsg += "\n" + str; richTextBox2.Invoke(receiveCallBack, strReceiveMsg); } bool sk = false; for (int i = 0; i < arrlist.Count; i++) { Zhuanfa zh = (Zhuanfa)arrlist[i]; if (socketSend.RemoteEndPoint.ToString() == zh.yonfuIP) { int jqq = zh.JQQ; jsQQ = jqq; for (int j = 0; j < arrlist.Count; j++) { Zhuanfa js = (Zhuanfa)arrlist[j]; if (jqq == js.FQQ) { sk = true; dicSocket[js.yonfuIP].Send(buffer, SocketFlags.None); } } } } if (sk == false)////离线转发客户端的线程(不停的转发消息使用定时器) { if (jsQQ != 0) { COMF duixian = new COMF(jsQQ, buffer); Lixianzhuanfa.Add(duixian); Invoke(zhangfalixian, "."); } } } } catch (Exception) { thrRecv.Abort(socketSend.RemoteEndPoint.ToString()); dicSocket.Remove(socketSend.RemoteEndPoint.ToString()); for (int i = 0; i < arrlist.Count; i++) { if (arrlist[i].yonfuIP == socketSend.RemoteEndPoint.ToString()) { arrlist.RemoveAt(i); this.richTextBox1.AppendText(socketSend.RemoteEndPoint.ToString() + "下线了,下线时间是:" + DateTime.Now + " \r \n"); Invoke(zhangfalixian, "."); shaxin = true; } } } } }