Ejemplo n.º 1
0
        //接收到客户端的数据事件
        private void process_receive(SocketAsyncEventArgs e)
        {
            // check if the remote host closed the connection
            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
            {
                AsyncUserToken            token  = e.UserToken as AsyncUserToken;
                System.Net.Sockets.Socket socket = token.Socket;



                //放入对应的robot的queue中
                int   socketId = m_robotSystem.get_socketToRobotMap()[socket];
                Robot robot    = m_robotSystem.get_robots()[socketId];

                byte[] data = new byte[e.BytesTransferred];
                Array.Copy(e.Buffer, e.Offset, data, 0, data.Length);
                lock (token.Buffer)
                {
                    token.Buffer.AddRange(data);
                }


                do// (packedDataOffset < e.BytesTransferred)
                {
                    byte[] lengthByte = token.Buffer.GetRange(0, 4).ToArray();

                    int length = BitConverter.ToInt32(lengthByte, 0);

                    if (length > token.Buffer.Count - 4)
                    {
                        break;
                    }

                    byte[] msgData = token.Buffer.GetRange(4, length).ToArray();
                    lock (token.Buffer)
                    {
                        token.Buffer.RemoveRange(0, length + 4);
                    }
                    //放入对应的robot的queue中
                    NetworkMsg netMsg = PBSerializer.deserialize <NetworkMsg>(msgData);
                    robot.m_clientSocket.dump_receive_queue(netMsg);
                } while (token.Buffer.Count > 4);


                Interlocked.Add(ref m_totalBytesRead, e.BytesTransferred);


                if (!socket.ReceiveAsync(e))
                {
                    process_receive(e);
                }
            }
            else
            {
                close_clientSocket(e);
            }
        }