Ejemplo n.º 1
0
        //Call Back,Socket检测客户端发送数据
        private void OnDataReceived(IAsyncResult asyn)
        {
            SocketPacket sp = (SocketPacket)asyn.AsyncState;

            try
            {
                int           receive = sp.CurrentSocket.EndReceive(asyn);
                char[]        chars   = new char[receive + 1];
                Decoder       decoder = Encoding.UTF8.GetDecoder();
                int           charLen = decoder.GetChars(sp.dataBuffer, 0, receive, chars, 0);
                System.String data    = new System.String(chars);
                //接受客户端数据

                //处理客户端数据!!!!!!!
                DealReceivedMsg(sp.ClientNO, data);

                //回复客户端
                //string replyMsg = sp.ClientNO.ToString();
                //byte[] byData = Encoding.UTF8.GetBytes(replyMsg);

                //Socket workerSocket = (Socket)sp.CurrentSocket;
                //workerSocket.Send(byData);

                WaitForData(sp.CurrentSocket, sp.ClientNO);
            }
            catch (ObjectDisposedException)
            {
                while (QueuePool.messages.Count > 0)
                { //提交未完成前,延迟处理🐶
                    System.Threading.Thread.Sleep(50);
                }

                logger.Error("数据接收时: Socket 已关闭。");
            }
            catch (SocketException se)
            {
                if (se.ErrorCode == 10054) // 连接被管道重置(客户端主动退出连接)
                {
                    string msg = "Client " + sp.ClientNO + " 断开连接" + "\n";
                    logger.Info(msg);

                    while (QueuePool.messages.Count > 0)
                    { //提交未完成前,延迟处理🐶
                        System.Threading.Thread.Sleep(50);
                    }

                    Globals.WorkerSocketList[sp.ClientNO - 1] = null;
                    RefreshConnectedClientList();
                }
                else
                {
                    logger.Error("数据接收时错误: " + se.Message);
                }
            }
        }
Ejemplo n.º 2
0
        //等待客户端的数据
        private void WaitForData(Socket skt, int clientNumber)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }

                SocketPacket socketPacket = new SocketPacket(skt, clientNumber);
                skt.BeginReceive(socketPacket.dataBuffer, 0, socketPacket.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, socketPacket);
            }
            catch (SocketException se)
            {
                logger.Warn("WaitForData has warn:" + se.Message);
            }
        }