/// <summary> /// 向单独的一个客户端发送消息 实现两个客户端通信 /// </summary> /// <param name="ip"></param> /// <param name="SendData"></param> public void SendToClient(IPEndPoint ip, string SendData) { try { Sockets sks = ClientList.Find(o => { return(o.Ip == ip); }); if (sks == null || !sks.Client.Connected) { Sockets ks = new Sockets(); //标识客户端下线 sks.ClientDispose = true; sks.ex = new Exception("客户端无连接"); pushSockets.Invoke(sks); } if (sks.Client.Connected) { //获取当前流进行写入. NetworkStream nStream = sks.nStream; if (nStream.CanWrite) { byte[] buffer = Encoding.UTF8.GetBytes(SendData); nStream.Write(buffer, 0, buffer.Length); } else { //避免流被关闭,重新从对象中获取流 nStream = sks.Client.GetStream(); if (nStream.CanWrite) { byte[] buffer = Encoding.UTF8.GetBytes(SendData); nStream.Write(buffer, 0, buffer.Length); } else { //如果还是无法写入,那么认为客户端中断连接. ClientList.Remove(sks); Sockets ks = new Sockets(); sks.ClientDispose = true; //如果出现异常,标识客户端下线 sks.ex = new Exception("客户端无连接"); pushSockets.Invoke(sks); //推送至netstat } } } } catch (Exception skex) { Sockets sks = new Sockets(); sks.ClientDispose = true; //如果出现异常,标识客户端退出 sks.ex = skex; pushSockets.Invoke(sks); //推送至netstat } }
/// <summary> /// 客户端加入队列 /// </summary> /// <param name="sk"></param> private void AddClientList(Sockets sk) { lock (obj) { Sockets sockets = ClientList.Find(o => { return(o.Ip == sk.Ip); }); if (sockets == null) { ClientList.Add(sk); } else { ClientList.Remove(sockets); ClientList.Add(sk); } } }
/// <summary> /// 关闭服务器 /// </summary> public override void Stop() { Sockets sks = new Sockets(); if (client != null) { client.Client.Shutdown(SocketShutdown.Both); Thread.Sleep(10); client.Close(); IsClose = true; client = null; } else { sks.ex = new Exception("客户端没有初始化.!"); } pushSockets.Invoke(sks);//推送至netstat }
/// <summary> /// 获取处理新的链接请求 /// </summary> private void GetAcceptTcpClient() { try { if (Listener.Pending()) //listen等待队列是否不为空 { semap.WaitOne(); //阻塞 //接收到挂起的客户端请求链接 TcpClient tcpClient = Listener.AcceptTcpClient(); //维护处理客户端队列 Socket socket = tcpClient.Client; NetworkStream stream = new NetworkStream(socket, true); Sockets sks = new Sockets(tcpClient.Client.RemoteEndPoint as IPEndPoint, tcpClient, stream); //增加sks客户端 sks.NewClientFlag = true; //推送新的客户端连接信息 pushSockets.Invoke(sks); //客户端异步接收数据 sks.nStream.BeginRead(sks.RecBuffer, 0, sks.RecBuffer.Length, new AsyncCallback(EndReader), sks); //加入客户端队列 this.AddClientList(sks); //链接成功后主动向客户端发送一条消息 if (stream.CanWrite) { byte[] buffer = Encoding.UTF8.GetBytes(this.InitMsg); stream.Write(buffer, 0, buffer.Length); //客户端netstat } semap.Release(); } } catch { return; } }