Exemplo n.º 1
0
        /// <summary>
        /// 作为客户端连接后要对AsyncSocketClient的处理--事件方法
        /// </summary>
        /// <param name="param"></param>
        /// <param name="client"></param>
        private void SocketConnectEvent(SocketEventParam param, AsyncSocketClient client)
        {
            try
            {
                if (param.Socket == null || client == null) //连接失败
                {
                }
                else
                {
                    lock (_clientGroup)
                    {
                        _clientGroup[client.ConnectSocket] = client;
                    }

                    client.OnSocketClose += Client_OnSocketClose;
                    client.OnReadData    += Client_OnReadData;
                    client.OnSendData    += Client_OnSendData;

                    _listReadEvent.PutObj(new SocketEventDeal(client, EN_SocketDealEvent.read));
                }
                _socketEventPool.PutObj(param);
            }
            catch (Exception ex)
            {
                NetLogger.Log($"SocketConnectEvent 异常 {ex.Message}***", ex);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="listenFault">监听失败的端口集合</param>
        /// <returns>true,存在监听失败的端口,false,反之</returns>
        public bool StartListen(out List <int> listenFault)
        {
            ServerStart = true;

            _clientPacketManage = new ClientPacketManage(this);
            _clientPacketManage.OnSocketPacketEvent += PutClientPacket;
            _netConnectManage.OnSocketConnectEvent  += SocketConnectEvent;

            _listenerList.Clear();
            Task.Run(() => NetReadProcess());
            Task.Run(() => NetSendProcess());
            Task.Run(() => NetPacketProcess());

            listenFault = new List <int>();
            foreach (ListenParam param in _listListenPort)
            {
                NetListener listener = new NetListener(this);
                listener.ListenParam     = param;
                listener.OnAcceptSocket += Listener_OnAcceptSocketClient;  //返回Listener生成的 AsyncSocketClient
                if (!listener.StartListen())
                {
                    listenFault.Add(param.Port);
                }
                else
                {
                    _listenerList.Add(listener);
                    NetLogger.Log($@"监听成功!端口:{param.Port}");
                }
            }

            return(listenFault.Count == 0);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Listener 生成的 AsyncSocketClient 回调方法
        /// </summary>
        /// <param name="listenParam">客户端参数</param>
        /// <param name="client">生成的客户端 实体类</param>
        private void Listener_OnAcceptSocketClient(ListenParam listenParam, AsyncSocketClient client)
        {
            try
            {
                lock (_clientGroup)
                {
                    _clientGroup[client.ConnectSocket] = client;
                }

                //给Client添加消息处理事件
                client.OnSocketClose += Client_OnSocketClose;
                client.OnReadData    += Client_OnReadData;
                client.OnSendData    += Client_OnSendData;
                client.OnSocketHeart += Client_OnSocketHeart;
                _listReadEvent.PutObj(new SocketEventDeal(client, EN_SocketDealEvent.read));
                var param = new SocketEventParam(client.ConnectSocket, EN_SocketEvent.accept)
                {
                    ClientInfo = client.ClientInfo
                };
                _socketEventPool.PutObj(param);
            }
            catch (Exception ex)
            {
                NetLogger.Log(@"Listener_OnAcceptSocket 异常", ex);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 对读取到的数据进行处理--Client异步读取完后会执行这个事件方法
        /// </summary>
        /// <param name="client">当前客户端类</param>
        /// <param name="readData">读取到的数据</param>
        private void Client_OnReadData(AsyncSocketClient client, byte[] readData, int offset, int count)
        {
            _listReadEvent.PutObj(new SocketEventDeal(client, EN_SocketDealEvent.read)); //读下一条
            try
            {
                var param = new SocketEventParam(client.ConnectSocket, EN_SocketEvent.read)
                {
                    ClientInfo = client.ClientInfo,
                    Data       = readData,
                    Offset     = offset,
                    Count      = count
                };

                if (client.ConnectSocket.Connected)
                {
                    _socketEventPool.PutObj(param);

                    lock (this)
                    {
                        ReadByteCount += readData.Length;
                    }
                }
            }
            catch (Exception ex)
            {
                NetLogger.Log($@"Client_OnReadData 异常 {ex.Message}***{ex.StackTrace}");
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// 开始数据接收
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="close"></param>
        public void StartReciveData(Socket socket, Action close = null)
        {
            try
            {
                // 初始化赋值
                skt = socket;
                OnDisReciveEvent += close;

                //回调开启连接事件
                OnStartConnected();
                OnStartConnectEvent?.Invoke();
                //首先是接收头4个字节确认包长
                //4可能太小了
                pack.headBuff = new byte[4];
                skt.BeginReceive(
                    pack.headBuff,
                    0,
                    4,
                    SocketFlags.None,
                    ReciveHeadData,
                    null);
            }
            catch (Exception e)
            {
                NetLogger.LogMsg($"开始接收数据错误:{e}", LogLevel.Error);
            }
        }
Exemplo n.º 6
0
    public void InitSvc()
    {
        client = new IClientSession <ClientSession, GameMsg>();
        client.StartCreate(SrvCfg.srvIP, SrvCfg.srvPort);


        client.SetLog(true, (string msg, int lv) =>
        {
            switch (lv)
            {
            case 0:
                msg = "Log:" + msg;
                NetLogger.LogMsg("消息 1:" + msg);
                break;

            case 1:
                msg = "Warn:" + msg;
                NetLogger.LogMsg("消息 2" + msg, LogLevel.Warn);
                break;

            case 2:
                msg = "Error:" + msg;
                NetLogger.LogMsg("消息 3:" + msg, LogLevel.Error);
                break;

            case 3:
                msg = "Info:" + msg;
                NetLogger.LogMsg(msg, LogLevel.Info);
                break;
            }
        });
        NetLogger.LogMsg("Init NetSvc...");
    }
Exemplo n.º 7
0
        // 每秒可以起送应对几千个客户端连接。接收对方监听采用AcceptAsync,也是异步操作。有单独的线程负责处理Accept。
        // 线程会同时投递多个AcceptAsync,就是已经建立好多个socket,等待客户端连接。当客户端到达时,可以迅速生成可用socket。
        /// <summary>
        /// 处理新的连接
        /// </summary>
        private void DealNewAccept()
        {
            try
            {
                //维持10个并发监听listener
                if (AcceptAsyncCount <= 10)
                {
                    StartAccept();
                }

                //检查新的Client是不是有问题
                while (true)
                {
                    _newSocketClientQueue.TryDequeue(out AsyncSocketClient client);
                    if (client == null)
                    {
                        break;
                    }

                    DealNewAccept(client);
                }
            }
            catch (Exception ex)
            {
                NetLogger.Log($@"DealNewAccept 异常", ex);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// 发送网络数据
        /// </summary>
        /// <param name="data"></param>
        public void SendMsg(byte[] data)
        {
            //创建流 准备异步写入发送
            NetworkStream ns = null;

            try
            {
                //指定写入的socket
                ns = new NetworkStream(skt);

                //判断是否可以支持写入消息
                if (ns.CanWrite)
                {
                    //开始异步写入
                    ns.BeginWrite(
                        data,
                        0,
                        data.Length,
                        SendDataAsync,
                        ns);
                }
            }
            catch (Exception e)
            {
                NetLogger.LogMsg($"SendDataError:{e}", LogLevel.Error);
            }
        }
Exemplo n.º 9
0
        void ClientConnectCB(IAsyncResult ar)
        {
            try
            {
                Socket clientSkt = skt.EndAccept(ar);
                T      session   = new T();
                //存储会话
                sessionLst.Add(session);
                //开始监听
                session.StartRcvData(clientSkt, () =>
                {
                    if (sessionLst.Contains(session))
                    {
                        //添加移除客户端的监听
                        RemoveSessionEvent?.Invoke(session);
                        //从列表中移除
                        sessionLst.Remove(session);
                    }
                });

                //添加委托监听
                AddSessionEvent?.Invoke(session);
            }
            catch (Exception e)
            {
                NetLogger.LogMsg("客户端 异步连接错误" + e.Message, LogLevel.Error);
            }
            skt.BeginAccept(new AsyncCallback(ClientConnectCB), skt);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 开始接收网络数据
        /// </summary>
        /// <param name="skt"></param>
        /// <param name="closeCB"></param>
        public void StartRcvData(Socket skt, Action closeCB)
        {
            try
            {
                this.skt     = skt;
                this.closeCB = closeCB;

                //连接成功的回调
                OnConnected();

                NetPkg pack = new NetPkg();
                //开始异步接收数据
                skt.BeginReceive(
                    pack.headBuff,
                    0,
                    pack.headLen,
                    SocketFlags.None,
                    new AsyncCallback(RcvHeadData),
                    pack);

                Console.WriteLine("接收数据:" + skt.ToString());
            }
            catch (Exception e)
            {
                NetLogger.LogMsg("开始接收数据错误:" + e.Message, LogLevel.Error);
            }
        }
Exemplo n.º 11
0
        //异步回调
        public override void ConnectAsync(IAsyncResult ar)
        {
            try
            {
                T client = new T();
                //这里结束接收 获取刚刚连接的socket
                Socket sk = skt.EndAccept(ar);

                //开始监听  第二个是加入结束事件
                client.StartReciveData(sk,
                                       () =>
                {
                    RemoveSession(client);
                    RemoveSessionEvent?.Invoke(client);
                    SessionList.Remove(client);
                });
                //存储会话
                SessionList.Add(client);
                AddSession(client);

                //添加委托监听
                AddSessionEvent?.Invoke(client);

                //开始新一轮接收连接
                skt.BeginAccept(ConnectAsync, null);
            }
            catch (Exception e)
            {
                NetLogger.LogMsg($"服务端连接回调错误:{e}", LogLevel.Error);
                skt?.BeginAccept(ConnectAsync, null);
            }
        }
Exemplo n.º 12
0
        public void OnConnectorDisconnectHandler(object sender, object disconnectionState)
        {
            IConnector connector = sender as IConnector;

            if (connector == null)
            {
                return;
            }

            connector.DisconnectEvent -= OnConnectorDisconnectHandler;

            TeamPainterTCPClient client = null;

            lock (_cSync)
            {
                long clientID;
                _clientConnectionAssociation.TryGetAndRemove(connector.UniqueID, out clientID);
                _clients.TryGetAndRemove(clientID, out client);
            }
            if (client != null)
            {
                client.Connector.DisconnectEvent  -= OnConnectorDisconnectHandler;
                client.Connector.ReceiveAction    -= OnReceveDataHandler;
                client.Connector.ReceiveComAction -= OnReceiveCommandHandler;
            }
            NetLogger.Log(connector.UniqueID + " is disconnected");

            DisconnectEvent?.Invoke(client, disconnectionState);
        }
Exemplo n.º 13
0
        public void Connect(IPAddress ip, int port)
        {
            NetLogger.LogInfo(logTag, $"Connecting to {ip}:{port}...");

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.BeginConnect(ip, port, OnConnected, socket);
        }
        public void OnDataReceived(byte[] buffer, long offset, long size)
        {
            lock (messageLocker)
            {
                messageBuffer.WriteBytes(buffer, (int)offset, (int)size);

                if (messageBuffer.Length > 0)
                {
                    byte[][] dataBytesArr = messageBuffer.ReadMessages();
                    if (dataBytesArr != null && dataBytesArr.Length > 0)
                    {
                        foreach (var dataBytes in dataBytesArr)
                        {
                            if (messageDecoder.DecodeMessage(dataBytes, out int msgID, out byte[] msgBytes))
                            {
                                ClientMessageData data = messageDataPool.Get();
                                data.MsgId    = msgID;
                                data.MsgBytes = msgBytes;
                                messageDatas.Add(data);
                            }
                            else
                            {
                                NetLogger.Error(LOG_TAG, "error");
                            }
                        }
                    }
                }
Exemplo n.º 15
0
        /// <summary>
        /// 发送网络数据
        /// </summary>
        /// <param name="data"></param>
        public void SendMsg(byte[] data)
        {
            //创建流,准备异步写入发送
            NetworkStream ns = null;

            try
            {
                //指定写入的socket
                ns = new NetworkStream(skt);
                //判断是否可以支持写入消息
                if (ns.CanWrite)
                {
                    //开始异步写入
                    ns.BeginWrite(
                        data,
                        0,
                        data.Length,
                        new AsyncCallback(SendCB),
                        ns);
                }
            }
            catch (Exception e)
            {
                NetLogger.LogMsg("发送数据错误:" + e.Message, LogLevel.Error);
            }
        }
Exemplo n.º 16
0
    private void ProcessMsg(GameMsg msg)
    {
        NetLogger.LogMsg("处理数据:" + msg.chatMsg);
        if (msg.err != (int)ERR.None)
        {
            switch ((ERR)msg.err)
            {
            case ERR.None:
                NetLogger.LogMsg("err   111");
                break;
            }
            return;
        }
        switch ((CMD)msg.cmd)
        {
        case CMD.HelloWorld:
            //接收到心跳包 刷新
            if (ackMgr != null)
            {
                ackMgr.UpdateOneHeat(client.Client);
            }
            break;

        case CMD.Chat:
            NetLogger.LogMsg($"接收到聊天信息{msg.chatMsg}");
            break;
        }
    }
Exemplo n.º 17
0
        void ClientConnectCB(IAsyncResult ar)
        {
            try
            {
                Socket clientSkt = skt.EndAccept(ar);
                T      session   = new T();
                sessionLst.Add(session);
                session.StartRcvData(clientSkt, () =>
                {
                    if (sessionLst.Contains(session))
                    {
                        sessionLst.Remove(session);
                    }
                });

                //开始为服务端添加上线和离线的监听事件
                session.OnClientOffline += ClientOfflineEvent;
                session.OnClientOnline  += ClientOnlineEvent;

                //开启扫描离线线程
                Thread client = new Thread(new ThreadStart(ScanClientConnectCB));
                client.IsBackground = true;
                client.Start();
                NetLogger.LogMsg("开始扫描离线程序");
            }
            catch (Exception e)
            {
                NetLogger.LogMsg(e.Message, LogLevel.Error);
            }
            skt.BeginAccept(new AsyncCallback(ClientConnectCB), skt);
        }
Exemplo n.º 18
0
        private void OnConnectCallback(IAsyncResult ar)
        {
            Socket sock = (Socket)ar.AsyncState;
            if (sock == null) return;

            IPEndPoint ep = null;
            try
            {
                sock.EndConnect(ar);
                ep = sock.RemoteEndPoint as IPEndPoint;

                _TCP = new ATCPConnector(sock, Uid64.CreateNewSync().Data, NetHelper.READ_BUFFER_BIG);
                _TCP.DisconnectEvent += OnDisconnectEventHandler;
                _TCP.ReceiveAction += OnReceveDataHandler;
                _TCP.ReceiveComAction += OnReceiveCommandHandler;
            }
            catch (SocketException ex){
                sock.Close();
                sock = null;
                NetLogger.Log(ex);
                return;
            }

            _isActive = true;
            if (ep != null) { NetLogger.Log("Connected to " + sock.RemoteEndPoint); }
            ConnectEvent?.Invoke(this, _TCP);
        }
Exemplo n.º 19
0
 public void Disconnect()
 {
     if (_TCP == null){
         NetLogger.Log("TCP connection module is not connected");
         return;
     }
     _TCP.Disconnect();
 }
Exemplo n.º 20
0
 private void OnReceveDataHandler(IConnector connector, byte[] data)
 {
     try
     {
         if (connector != null) { _commands.Execute(connector, data); }
     }
     catch (Exception ex) { NetLogger.Log(ex.ToString(), LogType.Exception); }
 }
Exemplo n.º 21
0
 private void OnReceiveCommandHandler(IConnector connector, ICommandArg arg)
 {
     try
     {
         if (connector != null) { _commands.Execute(connector, arg); }
     }
     catch (Exception ex) { NetLogger.Log(ex, LogType.Exception); }
 }
Exemplo n.º 22
0
 private void OnStartListener(object sender, EventArgs arg)
 {
     NetLogger.Log("TCP host start listening at" + _autorizator.Listener.ListenAddress);
     tbPort.Invoke((MethodInvoker) delegate { tbPort.ReadOnly = true; });
     tbIP.Invoke((MethodInvoker) delegate { tbIP.ReadOnly = true; });
     btnStartStop.Invoke((MethodInvoker) delegate { btnStartStop.Text = "Stop"; });
     pnlIndicator.Invoke((MethodInvoker) delegate { pnlIndicator.BackColor = Color.LimeGreen; });
     btnSettings.Invoke((MethodInvoker) delegate { btnSettings.Enabled = false; });
 }
Exemplo n.º 23
0
        public void DoUpdate(float deltaTime, float unscaleDeltaTime)
        {
            if (m_ClientSocket == null)
            {
                return;
            }
            ClientNetworkStatus curStatus = Status;

            if (m_PreStatus != curStatus)
            {
                if (curStatus == ClientNetworkStatus.Connecting)
                {
                    OnConnectingCallback?.Invoke();
                }
                else if (curStatus == ClientNetworkStatus.Connected)
                {
                    OnConnectedCallback?.Invoke();
                }
                else if (curStatus == ClientNetworkStatus.Disconnecting)
                {
                    OnDisconnectingCallback?.Invoke();
                }
                else if (curStatus == ClientNetworkStatus.Disconnected)
                {
                    OnDisconnectedCallback?.Invoke();
                }

                m_PreStatus = curStatus;
            }

            if (curStatus == ClientNetworkStatus.Connected)
            {
                lock (m_MessageLocker)
                {
                    foreach (var bytes in m_Messages)
                    {
                        int id = BitConverter.ToInt32(bytes, 0);
                        if (m_MessagHandlerDic.TryGetValue(id, out var callback))
                        {
                            byte[] contentBytes = new byte[0];
                            if (bytes.Length > sizeof(int))
                            {
                                contentBytes = new byte[bytes.Length - sizeof(int)];
                                Array.Copy(bytes, sizeof(int), contentBytes, 0, contentBytes.Length);
                            }
                            callback(contentBytes);
                        }
                        else
                        {
                            NetLogger.LogWarning(NetUtil.CLIENT_LOG_TAG, $"the handler of  id({id}) is not found");
                        }
                    }

                    m_Messages.Clear();
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// 接收包头数据
        /// </summary>
        /// <param name="ar"></param>
        protected void ReciveHeadData(IAsyncResult ar)
        {
            try
            {
                //接收数据长度等于0意味着断开连接
                //在断开的时候 异步会回调一次 直接调用EndReceive 会报错
                if (skt == null)
                {
                    return;
                }
                if (skt.Available == 0)
                {
                    Clear();
                    return;
                }

                int len = skt.EndReceive(ar);
                if (len > 0)
                {
                    pack.headIndex += len;
                    //这里如果是小于4的就是凑不成 就是分包了 要继续接收
                    if (pack.headIndex < pack.headLen)
                    {
                        //
                        skt.BeginReceive(
                            pack.headBuff,
                            pack.headIndex,
                            pack.headLen - pack.headIndex,
                            SocketFlags.None,
                            ReciveHeadData,
                            null);
                    }
                    //这里已经取出长度了
                    else
                    {
                        //赋值从那四个字节获取的byte[]的长度
                        pack.InitBodyBuff();
                        //进行真正的数据接收处理
                        skt.BeginReceive(
                            pack.bodyBuff,
                            0,
                            pack.bodyLen,
                            SocketFlags.None,
                            RcvBodyData,
                            null);
                    }
                }
                else
                {
                    Clear();
                }
            }
            catch (Exception e)
            {
                NetLogger.LogMsg($"接收:{e}", LogLevel.Error);
            }
        }
Exemplo n.º 25
0
        public void SendDataEx(Socket socket, byte[] data)
        {
            if (socket != null)
            {
                _netServer.SendData(socket, data);
                return;
            }

            NetLogger.Log(@"还没连接!");
        }
Exemplo n.º 26
0
        /// <summary>
        /// 给某个客户端发送消息
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public EN_SendDataResult SendData(Socket socket, byte[] data)
        {
            if (socket != null)
            {
                return(_netServer.SendData(socket, data));
            }

            NetLogger.Log(@"还没连接!");
            return(EN_SendDataResult.no_client);
        }
Exemplo n.º 27
0
 public void SendWith(Socket socket, byte[] bytes)
 {
     if (IsConnected && socket.Connected)
     {
         socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, OnSended, socket);
     }
     else
     {
         NetLogger.LogError(logTag, "the net is disconnected");
     }
 }
Exemplo n.º 28
0
 public void RegistMessageHandler(int id, Action <byte[]> messageHandler)
 {
     if (!m_MessagHandlerDic.ContainsKey(id))
     {
         m_MessagHandlerDic.Add(id, messageHandler);
     }
     else
     {
         NetLogger.LogError(NetUtil.CLIENT_LOG_TAG, "The handler has been added.id = " + id);
     }
 }
Exemplo n.º 29
0
 public void RegisterMessageHandler(int msgID, ServerMessageHandler handler)
 {
     if (!messageHandlerDic.ContainsKey(msgID))
     {
         messageHandlerDic.Add(msgID, handler);
     }
     else
     {
         NetLogger.Error(LOG_TAG, $"The handler({msgID}) has been registed");
     }
 }
Exemplo n.º 30
0
 public void StartAsClient(string ip, int port)
 {
     try
     {
         skt.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), new AsyncCallback(ServerConnectCB), skt);
         NetLogger.LogMsg("\n客户端启动成功!\n准备连接服务端......", LogLevel.Info);
     }
     catch (Exception e)
     {
         NetLogger.LogMsg(e.Message, LogLevel.Error);
     }
 }
Exemplo n.º 31
0
    public NetworkManager(string address, int port)
    {
        _address = address;
        _port = port;

        NetLogger log = new NetLogger();

        _signInStatus = SignInStatus.SignedOut;

        _theThread = new Thread(new ThreadStart(FFCManagerThreadFunc));
        _theThread.Name = "Network Manager";
        _theThread.Start();
    }