private unsafe void RecvClientSocketMethod() { while (!g_exitClientThread) { try { if (g_cListener == null || !g_cListener.Pending()) { Thread.Sleep(1); } else { Socket recvClientSocket = g_cListener.AcceptSocket(); if (recvClientSocket != null) { ClientSocketModel socket = new ClientSocketModel(); socket.LinkNo = LinkNoTool.GetLinkNo(); socket.Socket = recvClientSocket; socket.g_recvDataTime = DateTime.Now; socket.CleanUp(); lock (g_cdSockets) { g_cdSockets.Add(socket.LinkNo, socket); } Thread recvthread = new Thread(new ParameterizedThreadStart(RecvClientBufferMethod)); recvthread.Start(socket); MessageHandler handler = new MessageHandler(); handler.MessageCode = MessageCode.Success; handler.MessageInfo = string.Format("[{0}] 客户端成功连接,连接编号:{1},[IP]:{2}", DateTime.Now.ToString("HH:mm:ss"), socket.LinkNo, socket.Socket.RemoteEndPoint.ToString()); if (this.Connected != null) { Connected(handler); } } } } catch { } } }
/// <summary> /// 获取客户端套接字缓冲区数据 /// </summary> /// <param name="socket"></param> private unsafe void RecvClientBufferMethod(object socket) { ClientSocketModel clientsocket = (ClientSocketModel)socket; if (clientsocket != null && clientsocket.Socket != null) { while (!g_exitClientThread) { byte[] data = null; int len = 0; try { if (clientsocket.Socket == null || clientsocket.Socket.Available < clientsocket.g_recvWorkSize) { Thread.Sleep(1); } else { len = clientsocket.Socket.Receive((clientsocket.c_recvWorkHeader == null ? clientsocket.Buffer : clientsocket.g_recvWorkPacket), clientsocket.g_recvWorkOfs, clientsocket.g_recvWorkSize, SocketFlags.None); if (clientsocket.c_recvWorkHeader == null) { CLIENTWORK_PACKET_HEADER *header = (CLIENTWORK_PACKET_HEADER *)Marshal.UnsafeAddrOfPinnedArrayElement(clientsocket.Buffer, 0); if (header->bkey == CLIENTWORK_PACKET_HEADER.STX) { clientsocket.g_recvWorkSize = (header->wlen - len); clientsocket.g_recvWorkOfs = len; } clientsocket.c_recvWorkHeader = *header; clientsocket.g_recvWorkPacket = new byte[header->wlen]; Buffer.BlockCopy(clientsocket.Buffer, 0, clientsocket.g_recvWorkPacket, 0, len); if (clientsocket.g_recvWorkSize <= 0) { data = clientsocket.CleanUp(); } } else if ((len - clientsocket.g_recvWorkSize) <= 0) { data = clientsocket.CleanUp(); } } if (clientsocket.Socket != null && !clientsocket.Connected) { this.Close(clientsocket.LinkNo); } } catch { this.Close(clientsocket.LinkNo); Thread.CurrentThread.Abort(); } if (data != null) { MessageReceivedEventArgs args = new MessageReceivedEventArgs(); args.Buffer = data; args.Listener = this; args.LocalEP = clientsocket.Socket.LocalEndPoint; args.RemoteEP = clientsocket.Socket.RemoteEndPoint; args.RecivedType = MessgeRecivedType.ClientMessage; args.LinqNo = clientsocket.LinkNo; OnReceived(args); } } } }