Example #1
0
    void ThreadFunc()
    {
        Debug.Log("socket thread start");

        do
        {
            // connect
            try
            {
                socket.Connect(m_host, m_port);
            }
            catch
            {
                Debug.Log("socket connect failed");
                break;
            }

            // receive packet
            while (true)
            {
                if (mainThreadCloseSocket)
                {
                    break;
                }

                bool ret = socket.Poll(10, SelectMode.SelectRead);
                if (ret)
                {
                    if (socket.Available == 0)
                    {
                        Debug.Log("server disconnect the socket");
                        break;
                    }
                    else
                    {
                        byte[] receive = new byte[socket.Available];
                        int    len     = socket.Receive(receive);

                        receiveBuffer.Write(receive, len);

                        receiveBuffer.HandleReceive();
                    }
                }

                // send packet
                if (sendBuffer.offset > 0)
                {
                    //Debug.LogError("发送网络包到缓冲区");

                    byte[] buffer = new byte[sendBuffer.offset];

                    sendBuffer.Read(ref buffer, (int)sendBuffer.offset);

                    socket.Send(buffer);
                }
            }
        }while(false);

        Debug.Log("socket thread end");
    }
Example #2
0
        /// <summary>
        /// 读取消息,如果读取到一个完整的消息,返回true,没有获取完整消息,返回false
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool Read(SocketAsyncEventArgs e)
        {
            int          token  = ((AsyncUserToken)e.UserToken).Token;
            SocketBuffer buffer = SocketBuffers.GetOrAdd(token, t =>
            {
                return(new SocketBuffer(Config.MsgHandle, new ClientOption {
                    EndPoint = (IPEndPoint)e.AcceptSocket.RemoteEndPoint
                }));
            });

            return(buffer.Read(e));
        }