Esempio n. 1
0
        /// <summary>
        /// 解封包
        /// </summary>
        /// <param name="callback"></param>

        internal void Decode(Action <Packet> callback)
        {
            UserTokenSession UserToken = this.UserToken as UserTokenSession;
            int offset   = 0;
            var curBytes = MemoryBuffer.Span;

            while (offset < BytesTransferred)
            {
                try
                {
                    //测试服务端解析二进制流出现问题
                    //if (UserToken.Mode == SocketMode.Server)
                    //    throw new Exception();
                    offset += UserToken.Cache.LoadHead(curBytes.Slice(offset));
                    offset += UserToken.Cache.LoadBody(curBytes.Slice(offset));
                }
                catch
                {
                    UserToken.SendReconnect();
                    return;
                }

                if (UserToken.Cache.IsCompleted())
                {
                    PacketCommand(callback);
                }
            }
        }
Esempio n. 2
0
        public TcpClient(string host, int port)
        {
            this.Host = host;
            this.Port = port;

            UserTokenSession Session = new UserTokenSession();
            //初始化发送接套字
            SendEventArgs SendEvent = new SendEventArgs();

            SendEvent.Completed += AsyncDispatchCenter;
            SendEvent.UserToken  = Session;
            SendEvent.SendAction = ProcessSend;

            //初始化接收接套字
            ReceiveBuffer = new byte[BufferSize];
            ReceiveEventArgs ReceiveEvent = new ReceiveEventArgs();

            ReceiveEvent.Completed    += AsyncDispatchCenter;
            ReceiveEvent.UserToken     = Session;
            ReceiveEvent.ReceiveAction = ProcessReceive;
            Buffer.SetBuffer(ReceiveEvent, ReceiveBuffer);

            ShakeHandEvent               = new ShakeHandEventArgs(ReceiveEvent, SendEvent);
            ShakeHandEvent.Completed    += AsyncDispatchCenter;
            ShakeHandEvent.ConnectAction = StartConnect;
            Session.ShakeHandEvent       = ShakeHandEvent;
            Session.Mode             = ApplyMode.Client;
            ShakeHandEvent.UserToken = Session;
        }
Esempio n. 3
0
        bool PacketCommand(Action <Packet> bytes)
        {
            UserTokenSession UserToken = this.UserToken as UserTokenSession;

            switch (UserToken.Cache.Mode)
            {
            //如果是消息包就回调
            case MessageMode.MessageShort:
            case MessageMode.MessageInt:
                bytes?.Invoke(UserToken.Cache);
                break;

            //如果是请求断开
            case MessageMode.Disconect:
                SocketDisconect();
                break;

            //如果是请求重连
            case MessageMode.Reconnect:
                SocketReconect();
                break;
            }
            UserToken.Cache = null;
            return(true);
        }
Esempio n. 4
0
        /// <summary>
        /// 接收池
        /// </summary>
        /// <param name="BufferSize"></param>
        /// <param name="PoolSize"></param>
        /// <param name="AcceptCompleted"></param>
        /// <param name="IOCompleted"></param>
        public ShakeHandEventArgsPool(int BufferSize, int PoolSize, EventHandler <SocketAsyncEventArgs> DispatchCenter)
        {
            ShakeHandPool     = new ConcurrentStack <ShakeHandEventArgs>();
            ReceiveBufferPool = new BufferPool(BufferSize, PoolSize);
            SendBufferPool    = new BufferPool(BufferSize, PoolSize);
            for (int i = 0; i < PoolSize; i++)
            {
                UserTokenSession userToken        = new UserTokenSession();
                ReceiveEventArgs receiveEventArgs = new ReceiveEventArgs();
                receiveEventArgs.UserToken  = userToken;
                receiveEventArgs.Completed += DispatchCenter;
                Buffer.SetBuffer(receiveEventArgs, ReceiveBufferPool.Pop());

                SendEventArgs senEventArgs = new SendEventArgs();
                senEventArgs.UserToken  = userToken;
                senEventArgs.Completed += DispatchCenter;
                Buffer.SetBuffer(senEventArgs, SendBufferPool.Pop());

                ShakeHandEventArgs acceptEventArgs = new ShakeHandEventArgs(receiveEventArgs, senEventArgs);
                acceptEventArgs.Completed += DispatchCenter;
                acceptEventArgs.UserToken  = userToken;

                ShakeHandPool.Push(acceptEventArgs);
            }
        }
Esempio n. 5
0
        public void StartConnect()
        {
            Client = new Socket(AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            //设置连接地址
            ShakeHandEvent.RemoteEndPoint = GetEndPoint();
            UserTokenSession Session = (UserTokenSession)ShakeHandEvent.UserToken;

            Console.WriteLine("进行连接....是否处于正在连接中:" + Session.Connecting);
            Session.Connecting = true;
            if (!Client.ConnectAsync(ShakeHandEvent))
            {
                ProcessConnect(ShakeHandEvent);
            }
        }
Esempio n. 6
0
        void SocketDisconect()
        {
            UserTokenSession UserToken = this.UserToken as UserTokenSession;

            switch (UserToken.Mode)
            {
            case ApplyMode.Server:
                UserToken.SendDisconnect();
                break;

            case ApplyMode.Client:
                UserToken.Channel.Disconnect(false);
                break;
            }
        }
Esempio n. 7
0
        void SocketReconect()
        {
            UserTokenSession UserToken = this.UserToken as UserTokenSession;

            switch (UserToken.Mode)
            {
            case ApplyMode.Server:
                UserToken.SendReconnect();
                break;

            case ApplyMode.Client:
                UserToken.Channel.Disconnect(true);
                UserToken.ShakeHandEvent.ReConnect();
                break;
            }
        }
Esempio n. 8
0
        void ProcessReceive(SocketAsyncEventArgs e)
        {
            ReceiveEventArgs eventArgs = (ReceiveEventArgs)e;
            UserTokenSession UserToken = (UserTokenSession)eventArgs.UserToken;

            if (eventArgs.SocketError == SocketError.Success && eventArgs.BytesTransferred > 0)
            {
                //解码回调
                eventArgs.Decode((bytes) => OnCallBack?.Invoke(UserToken, bytes));

                //继续接收消息
                if (UserToken.Channel != null &&
                    !UserToken.Channel.ReceiveAsync(e))
                {
                    //此次接收没有接收完毕 递归接收
                    ProcessReceive(e);
                }
            }
        }
Esempio n. 9
0
        void ProcessSend(SocketAsyncEventArgs e)
        {
            SendEventArgs    eventArgs = (SendEventArgs)e;
            UserTokenSession UserToken = (UserTokenSession)eventArgs.UserToken;

            switch (eventArgs.SocketError)
            {
            //需要重新连接
            case SocketError.ConnectionReset:
                UserToken.NoSuccessMessage.Enqueue(eventArgs.MemoryBuffer.ToArray());
                StartConnect();
                break;

            //成功就不需要任何操作了
            case SocketError.Success:
                break;

            default:
                break;
            }
        }
Esempio n. 10
0
        void ProcessConnect(SocketAsyncEventArgs e)
        {
            ShakeHandEventArgs eventArgs = (ShakeHandEventArgs)e;
            UserTokenSession   Session   = (UserTokenSession)e.UserToken;

            //结束连接中状态
            Session.Connecting = false;
            switch (eventArgs.SocketError)
            {
            case SocketError.Success:
                Session.OperationTime = DateTime.Now;

                //异步监听连接完成后的操作
                ThreadPool.QueueUserWorkItem((e) => OnConnect?.Invoke(Session));

                //接收服务端传来的流
                if (!Session.Channel.ReceiveAsync(eventArgs.ReceiveEventArgs))
                {
                    ProcessReceive(eventArgs.ReceiveEventArgs);
                }

                //如果存在发送失败的消息 在重连之后
                while (Session.NoSuccessMessage.Count > 0)
                {
                    if (Session.NoSuccessMessage.TryDequeue(out var message))
                    {
                        Session.Channel.Send(message);
                    }
                }
                break;

            case SocketError.ConnectionRefused:
                break;

            default:
                break;
            }
        }
Esempio n. 11
0
        void ProcessReceive(SocketAsyncEventArgs e)
        {
            ReceiveEventArgs eventArgs = (ReceiveEventArgs)e;
            UserTokenSession UserToken = (UserTokenSession)eventArgs.UserToken;

            if (eventArgs.SocketError == SocketError.Success && eventArgs.BytesTransferred > 0)
            {
                //解码回调
                eventArgs.Decode((packet) =>
                {
                    if (packet.Mode == MessageMode.MessageShort ||
                        packet.Mode == MessageMode.MessageInt)
                    {
                        OnReceive?.Invoke(UserToken, packet);
                    }
                });

                //释放行为接套字的连接(此步骤无意义,只是以防万一)
                eventArgs.AcceptSocket = null;

                //继续接收消息
                if (!UserToken.Channel.ReceiveAsync(e))
                {
                    //此次接收没有接收完毕 递归接收
                    ProcessReceive(e);
                }
            }
            else
            {
                //客户端正常走这步
                OnExit?.Invoke(UserToken);
                //清理连接接套字
                UserToken.Clear();
                //推回接套字池
                ShakeHandEventPool.Push(UserToken.ShakeHandEvent);
            }
        }
Esempio n. 12
0
        void ProcessAccept(SocketAsyncEventArgs e)
        {
            ShakeHandEventArgs eventArgs = (ShakeHandEventArgs)e;

            //接收用户成功
            if (eventArgs.LastOperation == SocketAsyncOperation.Accept && eventArgs.SocketError == SocketError.Success)
            {
                //创建会话信息(当前会话)
                UserTokenSession UserToken = eventArgs.UserToken as UserTokenSession;
                var EndPoint = (IPEndPoint)eventArgs.AcceptSocket.RemoteEndPoint;
                var AllHost  = Dns.GetHostEntry(EndPoint.Address).AddressList;
                UserToken.UserHost                       = string.Join("|", AllHost.Select(x => x.ToString()).ToArray());
                UserToken.UserPort                       = ((IPEndPoint)(eventArgs.AcceptSocket.RemoteEndPoint)).Port;
                UserToken.Mode                           = ApplyMode.Server;
                UserToken.OperationTime                  = DateTime.Now;
                eventArgs.SendEventArgs.SendAction       = ProcessSend;
                eventArgs.ReceiveEventArgs.ReceiveAction = ProcessReceive;
                UserToken.ShakeHandEvent                 = eventArgs;
                OnConnect?.Invoke(UserToken);

                //异步接收客户端行为
                //异步接收客户端消息
                if (!UserToken.Channel.ReceiveAsync(UserToken.ShakeHandEvent.ReceiveEventArgs))
                {
                    ProcessReceive(UserToken.ShakeHandEvent.ReceiveEventArgs);
                }
            }
            else
            {
                //接收用户失败就清理后送回池
                eventArgs.Clear();
                ShakeHandEventPool.Push(eventArgs);
            }
            //继续接收下一个
            ShakeHandAsync();
        }
Esempio n. 13
0
 void ProcessSend(SocketAsyncEventArgs e)
 {
     SendEventArgs    eventArgs = (SendEventArgs)e;
     UserTokenSession UserToken = (UserTokenSession)eventArgs.UserToken;
 }