Beispiel #1
0
        /// <summary>
        /// 重连模块
        /// </summary>
        private void Reconnect()
        {
            if (_conncetType == ConncetType.Conncet)
            {
                TcpClientStateInfo(string.Format("已断开服务器{0}", IsReconnection ? ",准备重连" : ""), SocketState.Disconnect);
            }
            if (!IsReconnection)
            {
                return;
            }
            _reConnectCount++;//每重连一次重连的次数加1
            if (Client != null)
            {
                Client.WorkSocket.Close();
                Client = null;
            }
            if (_conncetType == ConncetType.Conncet)
            {
                _conncetType = ConncetType.ReConncet;

                //CommonMethod.EventInvoket(() => { ReconnectionStart(); });
            }
            _isStart = false;
            StartConnect();
        }
Beispiel #2
0
 /// <summary>
 /// 关闭相连的scoket以及关联的StateObject,释放所有的资源
 /// </summary>
 public void StopConnect()
 {
     IsReconnection = false;
     if (Client != null)
     {
         ShutdownClient(Client);
         Client.WorkSocket.Close();
     }
     _conncetType    = ConncetType.Conncet;
     _reConnectCount = 0;//前面三个初始化
 }
Beispiel #3
0
        /// <summary>
        /// 当连接服务器之后的回调函数
        /// </summary>
        /// <param name="ar">TcpClient</param>
        private void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                Socket socket = (Socket)ar.AsyncState;
                socket.EndConnect(ar);

                Client = new IClient(socket);
                Client.WorkSocket.BeginReceive(Client.BufferInfo.ReceivedBuffer, 0, Client.BufferInfo.ReceivedBuffer.Length, 0, new AsyncCallback(ReadCallback), Client);
                _conncetType = ConncetType.Conncet;
                TcpClientStateInfo(string.Format("已连接服务器"), SocketState.Connected);
                _reConnectCount = 0;
            }
            catch (SocketException ex)
            {
                string msg = ex.Message;
                if (ex.NativeErrorCode.Equals(10060))
                {
                    //无法连接目标主机
                    msg = string.Format("{0} 无法连接: error code {1}!", "", ex.NativeErrorCode);
                }
                else if (ex.NativeErrorCode.Equals(10061))
                {
                    msg = string.Format("{0} 主动拒绝正在重连: error code {1}!", "", ex.NativeErrorCode);
                }
                else if (ex.NativeErrorCode.Equals(10053))
                {
                    //读写时主机断开
                    msg = string.Format("{0} 主动断开连接: error code {1}! ", "", ex.NativeErrorCode);
                }
                else
                {
                    //其他错误
                    msg = string.Format("Disconnected: error code {0}!", ex.NativeErrorCode);
                }

                TcpClientErrorMsg(string.Format("连接服务器失败,错误原因:{0}", msg));
                Reconnect();
            }
        }