Пример #1
0
    void RecevieMessage()
    {
        while (true)
        {
            //在接收数据之前,判断socket连接是否断开
            if (clientSocket.Poll(10,SelectMode.SelectRead))
            {
                break;
            }
               
            //int length = clientSocket.Receive(data);
            //data 缓冲区默认为1024,一次性发送数据不应超过1024
            int length = clientSocket.Receive(data, data.Length, SocketFlags.None);
            //length 返回从系统缓冲实际读取的字节
            int readCount = 0;
            bool readEnd = false;
            if (length > 0)
            {

                do
                {
                    //本次实际读取字(可能包含多条命令)
                    byte[] msgbytes = data.Skip(readCount).Take(length).ToArray();
                    string msg = Encoding.UTF8.GetString(data, 0, length);
                    Debug.Log("Recevied Data length:" + length);
                    LoginInOutCodecs loginCodecs = new LoginInOutCodecs();


                    NadEvent nEvent = loginCodecs.getInCodecs().transform(msgbytes) as NadEvent;
                    if (null != nEvent)
                    {
                        /*
                            本次消息包含多条命令行
                            每条命令行包头为3个字节,
                            如果本次读取的(包头+包体),不大于等于socket消息长度,
                            说明还有消息存在,继续读取,
                        */
                        readCount += (3 + (nEvent.getSource() as MessageBuffer).getBuffer().Length);

                        if (length <= readCount)
                        {
                            readEnd = true;
                        }
                        else
                        {
                            //下条未读取消息的长度
                            length = length - readCount;
                        }
                        //本次消息派发(线程池启动派发)
                        ThreadPool.QueueUserWorkItem(dispatchEvent, nEvent);
                        
                    }
                    else
                    {
                        break;
                    }
                } while (!readEnd);
               
            }
            Debug.Log("Read network data...");
        // Decoding is not over, mostly because the whole frame  
        // was not received by the LengthFieldBasedFrameDecoder.
       }
    }
Пример #2
0
    void connectCallback(IAsyncResult asyncConnect)
    {
        if(clientSocket.Connected==true)
        {
            Debug.Log("connectSuccess");
            Debug.Log("Send Login info.....");
            LoginHelper loginHelper = new LoginHelper("[email protected]", "1000129", "user", ipaddress, port);
            LoginInOutCodecs loginCodecs = new LoginInOutCodecs();
            byte[] loginBytes = loginCodecs.getOutCodecs().transform(loginHelper.getLoginEvent()) as byte[];
            clientSocket.Send(loginBytes);
        }
      

    }