コード例 #1
0
ファイル: ZReceive.cs プロジェクト: MMoZi/ZNetWork
        private void ReceiveBody(IAsyncResult ar)
        {
            try
            {
                int len = conn.EndReceive(ar);
                if (len > 0)
                {
                    currBodyIndex += len;
                    if (currBodyIndex < headLength)
                    {
                        conn.BeginReceive(bodyCache, currBodyIndex, bodyLength - currBodyIndex, SocketFlags.None
                                          , new AsyncCallback(ReceiveBody), null);
                    }
                    else
                    {
                        string        str = ZNetConfig.encoding.GetString(bodyCache);
                        System.Object obj = JsonConvert.DeserializeObject(str);

                        OnEndReceive?.Invoke(connectId, obj);

                        clearCache();
                        initHeadCache();
                        conn.BeginReceive(headCache, 0, headLength, SocketFlags.None
                                          , new AsyncCallback(ReceiveHead), null);
                    }
                }
                else
                {
                    ZLogger.Debug(" ZReceive 003:用户" + connectId + " 连接已断开", LogType.Warning);
                    Close();
                }
            }
            catch (System.Exception ex)
            {
                ZLogger.Debug(" ZReceive 004:用户" + connectId + " 连接已断开", LogType.Warning);
                Close();
            }
        }
コード例 #2
0
        public void Start()
        {
            try
            {
                socket.BeginConnect(IPAddress.Parse(m_IP), m_Port, (ar) =>
                {
                    try
                    {
                        socket.EndConnect(ar);
                    }
                    catch (System.ObjectDisposedException)
                    {
                        ZLogger.Debug(" ZClient 001: 连接已断开", LogType.Warning);
                        return;
                    }
                    catch (System.Net.Sockets.SocketException) {
                        ZLogger.Debug(" ZClient 002: 服务器未启动", LogType.Warning);
                        return;
                    }
                    OnConnected?.Invoke();
                    ZReceive zr = new ZReceive(
                        connSocket: socket
                        , onDisConnected: (_) => OnDisConnected?.Invoke()
                        , onEndReceive: (_, obj) => OnEndReceive?.Invoke(obj)
                        );
                    zr.StartReceive();
                }, null);
            }
            catch (System.Exception)
            {
                ZLogger.Debug(" ZClient 003: 连接已断开", LogType.Warning);
                return;
            }

            ZLogger.Debug("     客户端初始化成功!   ");
        }