Ejemplo n.º 1
0
        /// <summary>
        /// Initialize net component and connect to remote server.
        /// </summary>
        /// <param name="remoteAddress">The address of remote server to connect.</param>
        /// <param name="remotePort">The port of remote server to connect.</param>
        public Boolean Initialize(String remoteAddress, Int32 remotePort)
        {
            // �ͻ��˴���IPV6��ʱ���߼�����Ҫ�õ�
#if UNITY_5_3_OR_NEWER
            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                String        newServerIp      = "";
                AddressFamily newAddressFamily = AddressFamily.InterNetwork;
                getIPType(remoteAddress, remotePort.ToString(), out newServerIp, out newAddressFamily);
                if (!string.IsNullOrEmpty(newServerIp))
                {
                    remoteAddress = newServerIp;
                }
            }
#endif

            // analyze the ip address and port info
            IPAddress myIp;
            if (IPAddress.TryParse(remoteAddress, out myIp))
            {
                //strMsg = String.Format("BuildPeer TryParse {0} success", remoteAddress);
                //Debug.WriteLine(strMsg);

                m_ipEndPoint = new IPEndPoint(myIp, remotePort);
            }
            else
            {
                //strMsg = String.Format("BuildPeer GetHostEntry {0} fail", remoteAddress);
                //Debug.WriteLine(strMsg);
                return(false);
            }

            // Do some cleanup if necessery
            if (State != ConnectionState.None)
            {
                Close();
            }

            // Clean all messages of last connection
            RecvQueue.Clear();

            // Clean all event args of last connection
            m_connEventArg    = new SocketAsyncEventArgs();
            m_receiveEventArg = new SocketAsyncEventArgs();

            // init event args
            m_connEventArg.Completed     += new EventHandler <SocketAsyncEventArgs>(OnCompletedForConnect);
            m_connEventArg.RemoteEndPoint = m_ipEndPoint;
            m_receiveEventArg.Completed  += new EventHandler <SocketAsyncEventArgs>(OnCompletedForReceive);
            m_receiveEventArg.SetBuffer(new byte[ProtoConst.MAX_PACKAGE_LENGTH], 0, ProtoConst.MAX_PACKAGE_LENGTH);

            // Change state
            State = ConnectionState.Connecting;

            // Create work resource
            RecvCache = new MessageBlock((int)ConnectionConst.CACHE_MAX_BYTE);

            StartConnectionWork();
            return(true);
        }
Ejemplo n.º 2
0
        public async Task Stop()
        {
            await _group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));

            //
            RecvQueue.Clear();
            SendQueue.Clear();
        }
Ejemplo n.º 3
0
        private async void Start(string serverIp, short serverPort)
        {
            Func <RT_MSG_TYPE, CipherContext, ICipher> getCipher = (id, context) =>
            {
                switch (context)
                {
                case CipherContext.RC_CLIENT_SESSION: return(_sessionCipher);

                case CipherContext.RSA_AUTH: return(AuthKey);

                default: return(null);
                }
            };

            _group        = new MultithreadEventLoopGroup();
            _scertHandler = new ScertServerHandler();

            // Initialize on connect
            _scertHandler.OnChannelActive += async(channel) =>
            {
                RecvQueue.Clear();
                SendQueue.Clear();
                State = ClientState.CONNECTED;

                await OnConnected(channel);
            };

            //
            _scertHandler.OnChannelInactive += async(channel) =>
            {
                await OnDisconnected(channel);
            };

            // Queue all incoming messages
            _scertHandler.OnChannelMessage += (channel, message) =>
            {
                RecvQueue.Enqueue(message);

                // Log if id is set
                if (message.CanLog())
                {
                    Logger.Info($"RECV {channel}: {message}");
                }
            };

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(_group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    pipeline.AddLast(new ScertEncoder());
                    pipeline.AddLast(new ScertIEnumerableEncoder());
                    pipeline.AddLast(new ScertTcpFrameDecoder(DotNetty.Buffers.ByteOrder.LittleEndian, Constants.MEDIUS_MESSAGE_MAXLEN, 1, 2, 0, 0, false));
                    pipeline.AddLast(new ScertDecoder(_sessionCipher, AuthKey));
                    pipeline.AddLast(_scertHandler);
                }));

                try
                {
                    _boundChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(serverIp), serverPort));
                }
                catch (Exception e)
                {
                    Logger.Error($"Failed to connect to server {e}");
                    State = ClientState.DISCONNECTED;
                    return;
                }
            }
            finally
            {
            }
        }