• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# ConnectState类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ConnectState的典型用法代码示例。如果您正苦于以下问题:C# ConnectState类的具体用法?C# ConnectState怎么用?C# ConnectState使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ConnectState类属于命名空间,在下文中一共展示了ConnectState类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: AlertWindow

 void AlertWindow(int windowId)
 {
     GUILayout.BeginVertical();
         string msg = "";
         switch (connectState) {
         case ConnectState.CONNECTING:
             msg = "Connecting...";
             break;
         case ConnectState.STARTING:
             msg = "Starting server...";
             break;
         case ConnectState.FAILED_CONN:
             msg = "Failed to connect to server. Please try again.";
             break;
         case ConnectState.FAILED_SERVE:
             msg = "Failed to start the server. Please try again.";
             break;
         }
         GUILayout.Label (msg);
         if (connectState == ConnectState.FAILED_CONN || connectState == ConnectState.FAILED_SERVE) {
             GUILayout.Space (10);
             if (GUILayout.Button("OK")) {
                 connectState = ConnectState.IDLE;
             }
         }
         GUILayout.EndVertical ();
 }
开发者ID:holycattle,项目名称:strawberryjam,代码行数:27,代码来源:Title.cs


示例2: Terminal

 //public Terminal( bool _carNetType, string _romVersion, string _Phone)
 //{
 //    //_Id = System.BitConverter.ToUInt32(bId, 0);
 //    _CarNetType = _carNetType;
 //    _romversion = _romVersion;
 //    _phone = _Phone;
 //    //获取分配的ID,或者已存在的ID
 //    //_gprsPeriod = _gprsperiod;
 //    //_Maker = _maker;
 //    //_RegTime = regTime;
 //    _state = ConnectState.Disconnect;//数据库获取,未链接的
 //    th = new System.Threading.Thread(new System.Threading.ThreadStart(CheckConnect));
 //    th.Start();
 //}
 /// <summary>
 /// 从数据库获取出来的
 /// </summary>
 /// <param name="bId"></param>
 /// <param name="_carNetType"></param>
 /// <param name="_romVersion"></param>
 /// <param name="_Phone"></param>
 /// <param name="_gprsperiod"></param>
 /// <param name="_maker"></param>
 /// <param name="regTime"></param>
 public Terminal(byte[] bId, bool _carNetType, string _romVersion, string _Phone, int _gprsperiod, Int64 _maker, DateTime regTime)
 {
     _Id = System.BitConverter.ToUInt32(bId, 0);
     _CarNetType = _carNetType;
     _romversion = _romVersion;
     _phone = _Phone;
     _gprsPeriod = _gprsperiod;
     _Maker = _maker;
     _RegTime = regTime;
     _state = ConnectState.Disconnect;//数据库获取,未链接的
     th = new System.Threading.Thread(new System.Threading.ThreadStart(CheckConnect));
     th.Start();
 }
开发者ID:dingxinbei,项目名称:Battery110Server,代码行数:37,代码来源:Data.cs


示例3: BeginConnect

        public void BeginConnect( string host, int port, Action<bool, INetworkConnection> callback )
        {
            ConnectState state = new ConnectState
                                 {
                                     Callback = callback,
                                     Socket = new Socket( AddressFamily.InterNetwork,
                                                          SocketType.Stream,
                                                          ProtocolType.Tcp )
                                 };

            //state.Socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Linger, false );
            //state.Socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.KeepAlive, false );
            state.Socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, NetworkConnection.BufferLength );
            state.Socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendBuffer, NetworkConnection.BufferLength );

            state.Socket.BeginConnect( host, port, HandleConnect, state );
        }
开发者ID:williamoneill,项目名称:Gallatin,代码行数:17,代码来源:NetworkConnectionFactory.cs


示例4: NetworkClient

 /// <summary>
 /// <para>Creates a new NetworkClient instance.</para>
 /// </summary>
 public NetworkClient()
 {
     this.m_NetworkConnectionClass = typeof(NetworkConnection);
     this.m_ServerIp = "";
     this.m_ClientId = -1;
     this.m_ClientConnectionId = -1;
     this.m_MessageHandlers = new NetworkMessageHandlers();
     this.m_AsyncConnect = ConnectState.None;
     this.m_RequestedServerHost = "";
     if (LogFilter.logDev)
     {
         Debug.Log("Client created version " + UnityEngine.Networking.Version.Current);
     }
     this.m_MsgBuffer = new byte[0xffff];
     this.m_MsgReader = new NetworkReader(this.m_MsgBuffer);
     AddClient(this);
 }
开发者ID:CarlosHBC,项目名称:UnityDecompiled,代码行数:20,代码来源:NetworkClient.cs


示例5: DownloadFile

 public bool DownloadFile(Uri uri, String fileName)
 {
     this.fileName = fileName;
     statusCode = "Unknown";
     contentLength = 0;
     try {
         WebRequest webRequest = HttpWebRequest.Create(uri);
         webRequest.BeginGetResponse(new AsyncCallback(requestCallBack), webRequest);
         State = ConnectState.Connect;
     } catch (Exception e) {
         Console.WriteLine(e);
         State = ConnectState.Failed;
         ErrorEventArgs args = new ErrorEventArgs();
         args.Message = e.Message;
         OnErrorOccurred(args);
         return false;
     }
     return true;
 }
开发者ID:khiraiwa,项目名称:psm-avi_movie_player,代码行数:19,代码来源:HttpRequestUtil.cs


示例6: _onConnectStatus

		public void _onConnectStatus(ConnectState state)
		{
			KBEngine.Event.deregisterIn(this);
			
			bool success = (state.error == "" && valid());
			if(success)
			{
				Dbg.DEBUG_MSG(string.Format("NetworkInterface::_onConnectStatus(), connect to {0} is success!", state.socket.RemoteEndPoint.ToString()));
				_packetReceiver = new PacketReceiver(this);
				_packetReceiver.startRecv();
			}
			else
			{
				Dbg.ERROR_MSG(string.Format("NetworkInterface::_onConnectStatus(), connect is error! ip: {0}:{1}, err: {2}", state.connectIP, state.connectPort, state.error));
			}
			
			Event.fireOut("onConnectStatus", new object[]{success});
			
			if (state.connectCB != null)
				state.connectCB(state.connectIP, state.connectPort, success, state.userData);
		}
开发者ID:yangguodang0502,项目名称:kbengine_unity3d_plugins,代码行数:21,代码来源:NetworkInterface.cs


示例7: connectTo

        public void connectTo(string ip, int port, ConnectCallback callback, object userData)
        {
            if (valid())
                throw new InvalidOperationException( "Have already connected!" );

            if(!(new Regex( @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip))
            {
                IPHostEntry ipHost = Dns.GetHostEntry (ip);
                ip = ipHost.AddressList[0].ToString();
            }

            // Security.PrefetchSocketPolicy(ip, 843);
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, KBEngineApp.app.getInitArgs().getRecvBufferSize() * 2);
            _socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.SendBuffer, KBEngineApp.app.getInitArgs().getSendBufferSize() * 2);
            _socket.NoDelay = true;

            ConnectState state = new ConnectState();
            state.connectIP = ip;
            state.connectPort = port;
            state.connectCB = callback;
            state.userData = userData;
            state.socket = _socket;
            state.networkInterface = this;

            Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ...");

            // 先注册一个事件回调,该事件在当前线程触发
            Event.registerIn("_onConnectStatus", this, "_onConnectStatus");

            try
            {
                _socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), new AsyncCallback(connectCB), state);
            }
            catch (Exception e)
            {
                state.error = e.ToString();
                Event.fireIn("_onConnectStatus", new object[]{state});
            }
        }
开发者ID:GamesDesignArt,项目名称:kbengine_unity3d_plugins,代码行数:40,代码来源:NetworkInterface.cs


示例8: Update

    void Update()
    {
        // DRAG OBJECT ORIGIN STATES
        if (thisConnectState == ConnectState.DragObjOriginReturned)
        {

            Debug.Log (this + " is returned");

            thisConnectState = ConnectState.DragObjOriginPresent;

            this.renderer.enabled = true;

        }

        if (thisConnectState == ConnectState.DragObjOriginLifted)
        {

            Debug.Log (this + " is lifted");

            thisConnectState = ConnectState.DragObjOriginNotPresent;

            this.renderer.enabled = false;

        }

        // DRAG OBJECT TARGET STATES

        if (thisConnectState == ConnectState.DragObjTargetConnectionMade)
        {

            Debug.Log (this + " is connected");

            thisConnectState = ConnectState.DragObjTargetConnected;

            renderer.material.SetTextureOffset("_MainTex", new Vector2(0.5f,0f));

        }
    }
开发者ID:JonathanBauer,项目名称:HarryTheKangaroo,代码行数:38,代码来源:GameObjectMode.cs


示例9: FromConnectState

 /// <summary>
 /// Creates a new instance of the TcpState class from an exisiting <see cref="ConnectState"/>.
 /// </summary>
 /// <param name="cs">The <see cref="ConnectState"/></param>
 /// <param name="stream">The <see cref="Stream"/> of the connection</param>
 /// <param name="buffer">The buffer to hold the response</param>
 /// <returns><see cref="TcpState"/></returns>
 public static ResponseState FromConnectState(ConnectState cs, Stream stream, byte[] buffer)
 {
     ResponseState state = new ResponseState();
     state.Request = cs.Request;
     state.Stream = stream;
     state.Buffer = buffer;
     return state;
 }
开发者ID:iwaim,项目名称:growl-for-windows,代码行数:15,代码来源:CometClient.cs


示例10: ProcessConnect

        /// <summary>
        /// Callback method for asynchronous connect operation.
        /// </summary>
        private void ProcessConnect(ConnectState connectState)
        {
            ReceiveState receiveState = null;
            SendState sendState = null;

            try
            {
                // Quit if this connection loop has been cancelled
                if (connectState.Token.Cancelled)
                    return;

                // Increment the number of connection attempts that
                // have occurred in this asynchronous connection loop
                connectState.ConnectionAttempts++;

                // Check the SocketAsyncEventArgs for errors during the asynchronous connection attempt
                if (connectState.ConnectArgs.SocketError != SocketError.Success)
                    throw new SocketException((int)connectState.ConnectArgs.SocketError);

                // Set the size of the buffer used by the socket to store incoming data from the server
                connectState.Socket.ReceiveBufferSize = ReceiveBufferSize;

                if (m_integratedSecurity)
                {
#if !MONO
                    // Check the state of cancellation one more time before
                    // proceeding to the next step of the connection loop
                    if (connectState.Token.Cancelled)
                        return;

                    // Create the SslStream object used to perform
                    // send and receive operations on the socket
                    connectState.NetworkStream = new NetworkStream(connectState.Socket, false);
                    connectState.NegotiateStream = new NegotiateStream(connectState.NetworkStream, true);
                    connectState.NegotiateStream.BeginAuthenticateAsClient(m_networkCredential ?? (NetworkCredential)CredentialCache.DefaultCredentials, string.Empty, ProcessIntegratedSecurityAuthentication, connectState);
#endif
                }
                else
                {
                    // Initialize the SocketAsyncEventArgs for receive operations
                    connectState.ReceiveArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction();
                    connectState.ReceiveArgs.SetBuffer(new byte[ReceiveBufferSize], 0, ReceiveBufferSize);

                    if (m_payloadAware)
                        connectState.ReceiveArgs.Completed += (sender, args) => ProcessReceivePayloadAware((ReceiveState)args.UserToken);
                    else
                        connectState.ReceiveArgs.Completed += (sender, args) => ProcessReceivePayloadUnaware((ReceiveState)args.UserToken);

                    // Initialize the SocketAsyncEventArgs for send operations
                    connectState.SendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction();
                    connectState.SendArgs.SetBuffer(new byte[SendBufferSize], 0, SendBufferSize);
                    connectState.SendArgs.Completed += (sender, args) => ProcessSend((SendState)args.UserToken);

                    // Initialize state object for the asynchronous send loop
                    sendState = new SendState();
                    sendState.Token = connectState.Token;
                    sendState.Socket = connectState.Socket;
                    sendState.ReceiveArgs = connectState.ReceiveArgs;
                    sendState.SendArgs = connectState.SendArgs;
                    sendState.SendArgs.UserToken = sendState;

                    // Store sendState in m_sendState so that calls to Disconnect
                    // and Dispose can dispose resources and cancel asynchronous loops
                    m_sendState = sendState;

                    // Check the state of cancellation one more time before
                    // proceeding to the next step of the connection loop
                    if (connectState.Token.Cancelled)
                        return;

                    // Notify of established connection
                    m_connectWaitHandle.Set();
                    OnConnectionEstablished();

                    // Initialize state object for the asynchronous receive loop
                    receiveState = new ReceiveState();
                    receiveState.Token = connectState.Token;
                    receiveState.Socket = connectState.Socket;
                    receiveState.Buffer = connectState.ReceiveArgs.Buffer;
                    receiveState.ReceiveArgs = connectState.ReceiveArgs;
                    receiveState.ReceiveArgs.UserToken = receiveState;
                    receiveState.SendArgs = connectState.SendArgs;

                    // Store receiveState in m_receiveState so that calls to Disconnect
                    // and Dispose can dispose resources and cancel asynchronous loops
                    m_receiveState = receiveState;

                    // Start receiving data
                    if (m_payloadAware)
                        ReceivePayloadAwareAsync(receiveState);
                    else
                        ReceivePayloadUnawareAsync(receiveState);

                    // Further socket interactions are handled through the ReceiveArgs
                    // and SendArgs objects, so the ConnectArgs is no longer needed
                    connectState.ConnectArgs.Dispose();
                }
//.........这里部分代码省略.........
开发者ID:GridProtectionAlliance,项目名称:gsf,代码行数:101,代码来源:TcpClient.cs


示例11: ConnectAsync

        /// <summary>
        /// Connects the <see cref="TcpClient"/> to the server asynchronously.
        /// </summary>
        /// <exception cref="InvalidOperationException">Attempt is made to connect the <see cref="TcpClient"/> when it is not disconnected.</exception>
        /// <returns><see cref="WaitHandle"/> for the asynchronous operation.</returns>
        public override WaitHandle ConnectAsync()
        {
            ConnectState connectState = null;

            Match endpoint;
            string integratedSecuritySetting;

            if (CurrentState == ClientState.Disconnected && !m_disposed)
            {
                try
                {
                    // If we do not already have a wait handle to use
                    // for connections, get one from the base class
                    if ((object)m_connectWaitHandle == null)
                        m_connectWaitHandle = (ManualResetEvent)base.ConnectAsync();

                    // Create state object for the asynchronous connection loop
                    connectState = new ConnectState();

                    // Store connectState in m_connectState so that calls to Disconnect
                    // and Dispose can dispose resources and cancel asynchronous loops
                    m_connectState = connectState;

                    OnConnectionAttempt();
                    m_connectWaitHandle.Reset();

                    // Overwrite config file if integrated security exists in connection string
                    if (m_connectData.TryGetValue("integratedSecurity", out integratedSecuritySetting))
                        m_integratedSecurity = integratedSecuritySetting.ParseBoolean();
#if MONO
                    // Force integrated security to be False under Mono since it's not supported
                    m_integratedSecurity = false;
#endif

                    // Initialize state object for the asynchronous connection loop
                    endpoint = Regex.Match(m_connectData["server"], Transport.EndpointFormatRegex);

                    connectState.ConnectArgs.RemoteEndPoint = Transport.CreateEndPoint(endpoint.Groups["host"].Value, int.Parse(endpoint.Groups["port"].Value), m_ipStack);
                    connectState.ConnectArgs.SocketFlags = SocketFlags.None;
                    connectState.ConnectArgs.UserToken = connectState;
                    connectState.ConnectArgs.Completed += (sender, args) => ProcessConnect((ConnectState)args.UserToken);

                    // Create client socket
                    connectState.Socket = Transport.CreateSocket(m_connectData["interface"], 0, ProtocolType.Tcp, m_ipStack, m_allowDualStackSocket);

                    // Initiate the asynchronous connection loop
                    ConnectAsync(connectState);
                }
                catch (Exception ex)
                {
                    // Log exception during connection attempt
                    OnConnectionException(ex);

                    // Terminate the connection
                    if ((object)connectState != null)
                        TerminateConnection(connectState.Token);

                    // Ensure that the wait handle is set so that operations waiting
                    // for completion of the asynchronous connection loop can continue
                    if ((object)m_connectWaitHandle != null)
                        m_connectWaitHandle.Set();
                }
                finally
                {
                    // If the operation was cancelled during execution,
                    // make sure to dispose of erroneously allocated resources
                    if ((object)connectState != null && connectState.Token.Cancelled)
                        connectState.Dispose();
                }
            }

            // Return the wait handle that signals completion
            // of the asynchronous connection loop
            return m_connectWaitHandle;
        }
开发者ID:GridProtectionAlliance,项目名称:gsf,代码行数:80,代码来源:TcpClient.cs


示例12: ConnectTDPCallback

        private void ConnectTDPCallback(IAsyncResult ar)
        {
            if (closed)
            {
                return;
            }
            try
            {
                remoteTDP.EndConnect(ar);

                speedTester.EndConnect();
                server.ServerSpeedLog().AddConnectTime((int)(speedTester.timeConnectEnd - speedTester.timeConnectBegin).TotalMilliseconds);

                ConnectState _state = this.State;
                if (_state == ConnectState.CONNECTING)
                {
                    this.State = ConnectState.CONNECTED;
                    StartPipe();
                }
                else if (_state == ConnectState.CONNECTED)
                {
                    //ERROR
                }
            }
            catch (Exception e)
            {
                LogSocketException(e);
                if (!Logging.LogSocketException(server.remarks, server.server, e))
                    Logging.LogUsefulException(e);
                this.Close();
            }
        }
开发者ID:yaoliyc,项目名称:shadowsocks-csharp,代码行数:32,代码来源:Local.cs


示例13: Connect

 private void Connect()
 {
     lock (server)
     {
         server.ServerSpeedLog().AddConnectTimes();
         if (this.State == ConnectState.HANDSHAKE)
         {
             this.State = ConnectState.CONNECTING;
         }
         server.GetConnections().AddRef(this.connection);
         encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
         encryptorUDP = EncryptorFactory.GetEncryptor(server.method, server.password);
     }
     this.obfs = ObfsFactory.GetObfs(server.obfs);
     closed = false;
     {
         IPAddress ipAddress;
         string serverURI = server.server;
         int serverPort = server.server_port;
         if (socks5RemotePort > 0)
         {
             serverURI = socks5RemoteHost;
             serverPort = socks5RemotePort;
         }
         bool parsed = IPAddress.TryParse(serverURI, out ipAddress);
         if (!parsed)
         {
             //IPHostEntry ipHostInfo = Dns.GetHostEntry(serverURI);
             //ipAddress = ipHostInfo.AddressList[0];
             if (server.DnsBuffer().isExpired(serverURI))
             {
                 Dns.BeginGetHostEntry(serverURI, new AsyncCallback(DnsCallback), null);
                 return;
             }
             else
             {
                 ipAddress = server.DnsBuffer().ip;
             }
         }
         //else
         BeginConnect(ipAddress, serverPort);
     }
 }
开发者ID:yaoliyc,项目名称:shadowsocks-csharp,代码行数:43,代码来源:Local.cs


示例14: Start

 public void Start(byte[] firstPacket, int length)
 {
     this._firstPacket = firstPacket;
     this._firstPacketLength = length;
     if (socks5RemotePort > 0)
     {
         autoSwitchOff = false;
     }
     if (this.State == ConnectState.READY)
     {
         this.State = ConnectState.HANDSHAKE;
         this.HandshakeReceive();
     }
 }
开发者ID:yaoliyc,项目名称:shadowsocks-csharp,代码行数:14,代码来源:Local.cs


示例15: MapLoading

        /*
        =====================
        CL_MapLoading

        A local server is starting to load a map, so update the
        screen to let the user know about it, then dump all client
        memory on the hunk from cgame, ui, and renderer
        =====================
        */
        internal void MapLoading()
        {
            if (!Common.Instance.cl_running.Bool)
                return;

            // if we are already connected to the local host, stay connected
            if ((int)state >= (int)ConnectState.CONNECTED && servername.Equals("localhost"))
            {
                state = ConnectState.CONNECTED;  // so the connect screen is drawn
                clc.serverMessage = "";
                cl.gamestate.data.Clear();
                clc.lastPacketSentTime = -9999;
                UpdateScreen();
            }
            else
            {
                CVars.Instance.Set("nextmap", "");
                Disconnect(true);
                servername = "localhost";
                state = ConnectState.CHALLENGING;    // so the connect screen is drawn
                UpdateScreen();
                clc.connectTime = -3000;
                IPEndPoint end = new IPEndPoint(IPAddress.Parse("127.0.0.1"), Net.Instance.net_port.Integer);
                clc.serverAddress = end; // cls.servername FIX
                // we don't need a challenge on the localhost
                CheckForResend();
            }
        }
开发者ID:maesse,项目名称:CubeHags,代码行数:37,代码来源:Client.cs


示例16: Shutdown

        public void Shutdown()
        {
            if (this.State != ConnectState.END && this.State != ConnectState.DISCONNECTING)
            {
                this.State = ConnectState.CONNECTIONEND;
            }

            CallbackSendInvoke();
            if (DataCallbackRecvInvoke())
                return;
        }
开发者ID:JarodWan,项目名称:shadowsocks-csharp,代码行数:11,代码来源:TDP.cs


示例17: Close

        public void Close()
        {
            lock (this)
            {
                if (closed)
                {
                    return;
                }
                closed = true;
            }
            try
            {
                if (TryReconnect())
                    return;
                lock (server)
                {
                    if (this.State != ConnectState.END)
                    {
                        this.State = ConnectState.END;
                        server.ServerSpeedLog().AddDisconnectTimes();
                        server.GetConnections().DecRef(this.connection);
                        server.ServerSpeedLog().AddSpeedLog(new TransLog((int)speedTester.GetAvgDownloadSpeed(), DateTime.Now));
                    }
                    getCurrentServer = null;
                    ResetTimeout(0);
                    speedTester = null;
                }
                CloseSocket(ref connection);
                CloseSocket(ref connectionUDP);
                CloseSocket(ref remote);
                CloseSocket(ref remoteUDP);
                if (remoteTDP != null)
                {
                    try
                    {
                        remoteTDP.Shutdown();
                        //remoteTDP.Close();
                    }
                    catch (Exception e)
                    {
                        Logging.LogUsefulException(e);
                    }
                    remoteTDP = null;
                }

                if (obfs != null)
                {
                    obfs.Dispose();
                    obfs = null;
                }
                lock (encryptionLock)
                {
                    lock (decryptionLock)
                    {
                        if (encryptor != null)
                            ((IDisposable)encryptor).Dispose();
                        if (encryptorUDP != null)
                            ((IDisposable)encryptorUDP).Dispose();
                    }
                }
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
            }
        }
开发者ID:yaoliyc,项目名称:shadowsocks-csharp,代码行数:66,代码来源:Local.cs


示例18: CheckForResend

        /*
        =================
        CL_CheckForResend

        Resend a connect message if the last one has timed out
        =================
        */
        void CheckForResend()
        {
            // resend if we haven't gotten a reply yet
            if (state != ConnectState.CONNECTING && state != ConnectState.CHALLENGING)
            {
                return;
            }

            if (realtime - clc.connectTime < 3000)
            {
                return;
            }

            clc.connectTime = realtime;
            clc.connectPacketCount++;

            if (clc.connectPacketCount == 5)
            {
                Disconnect(true);
                state = ConnectState.DISCONNECTED;
                clc.connectPacketCount = 0;
                Common.Instance.WriteLine("Could not connect: ^1No response from server.");
                return;
            }

            switch (state)
            {
                case ConnectState.CONNECTING:
                    string data = "getchallenge " + clc.challenge;
                    Net.Instance.OutOfBandMessage(Net.NetSource.CLIENT,clc.serverAddress, data);
                    Common.Instance.WriteLine("Connecting{0} to {1}...", (clc.connectPacketCount <= 1) ? "" : "(retry " + clc.connectPacketCount +")", clc.serverAddress.ToString());
                    break;
                case ConnectState.CHALLENGING:
                    // sending back the challenge
                    int port = CVars.Instance.VariableIntegerValue("net_qport");

                    data = "connect ";
                    string cs = CVars.Instance.InfoString(CVarFlags.USER_INFO);
                    cs = Info.SetValueForKey(cs, "qport", ""+port);
                    cs = Info.SetValueForKey(cs, "challenge", ""+clc.challenge);

                    data += '"' + cs + '"';

                    Net.Instance.OutOfBandMessage(Net.NetSource.CLIENT, clc.serverAddress, data);
                    // the most current userinfo has been sent, so watch for any
                    // newer changes to userinfo variables
                    CVars.Instance.modifiedFlags &= ~CVarFlags.USER_INFO;

                    Common.Instance.WriteLine("^8Connection Ok, got challenge.");
                    break;

                default:

                    break;
            }
        }
开发者ID:maesse,项目名称:CubeHags,代码行数:63,代码来源:Client.cs


示例19: BeginConnect

        private void BeginConnect(IPAddress ipAddress, int serverPort)
        {
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, serverPort);
            remoteUDPEndPoint = remoteEP;

            if (server.tcp_over_udp && connectionUDP == null)
            {
                remoteTDP = new TDPHandler();
            }
            if (socks5RemotePort != 0
                || connectionUDP == null && !server.tcp_over_udp
                || connectionUDP != null && server.udp_over_tcp)
            {
                remote = new Socket(ipAddress.AddressFamily,
                    SocketType.Stream, ProtocolType.Tcp);
                remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            }

            if (connectionUDP != null && !server.udp_over_tcp)
            {
                try
                {
                    remoteUDP = new Socket(ipAddress.AddressFamily,
                        SocketType.Dgram, ProtocolType.Udp);
                    remoteUDP.Bind(new IPEndPoint(ipAddress.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0));
                }
                catch (SocketException)
                {
                    remoteUDP = null;
                }
            }

            if (remoteTDP != null && server.tcp_over_udp && socks5RemotePort == 0)
            {
                speedTester.BeginConnect();
                remoteTDP.BeginConnect(server.method, server.password, remoteEP, "", 0,
                    new AsyncCallback(ConnectCallback), null);
            }
            else
            {
                // Connect to the remote endpoint.
                if (socks5RemotePort == 0 && connectionUDP != null && !server.udp_over_tcp)
                {
                    ConnectState _state = this.State;
                    if (_state == ConnectState.CONNECTING)
                    {
                        this.State = ConnectState.CONNECTED;
                        StartPipe();
                    }
                    else if (_state == ConnectState.CONNECTED)
                    {
                        //ERROR
                    }
                }
                else
                {
                    speedTester.BeginConnect();
                    remote.BeginConnect(remoteEP,
                        new AsyncCallback(ConnectCallback), null);
                }
            }
        }
开发者ID:yaoliyc,项目名称:shadowsocks-csharp,代码行数:62,代码来源:Local.cs


示例20: CL_Connect_f

        void CL_Connect_f(string[] tokens)
        {
            if (tokens.Length != 2)
            {
                Common.Instance.WriteLine("Connect usage: connect server\n");
                return;
            }

            string server = tokens[1];
            clc.serverMessage = "";

            if (Common.Instance.sv_running.Integer == 1 && server != "localhost")
            {
                // If running a server, shut it down
                Server.Instance.Shutdown("Server quit");
            }

            // Make sure the local server is killed
            CVars.Instance.Set("sv_killserver", "1");
            Server.Instance.Frame(0);

            Disconnect(true);

            IPEndPoint endp = Net.StringToAddr(server);
            if (endp == null)
            {
                Common.Instance.WriteLine("^1Connect failed: Could not lookup {0}", server);
                state = ConnectState.DISCONNECTED;
                return;
            }

            servername = server;
            clc.serverAddress = endp;
            state = ConnectState.CONNECTING;
            clc.connectTime = -99999;
            clc.connectPacketCount = 0;
        }
开发者ID:maesse,项目名称:CubeHags,代码行数:37,代码来源:Client.cs



注:本文中的ConnectState类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Connected类代码示例发布时间:2022-05-24
下一篇:
C# Connect类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap