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 (); }
//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(); }
/// <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); }
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 ); }
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; }
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); }
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}); } }
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)); } }
public void Shutdown() { if (this.State != ConnectState.END && this.State != ConnectState.DISCONNECTING) { this.State = ConnectState.CONNECTIONEND; } CallbackSendInvoke(); if (DataCallbackRecvInvoke()) return; }
protected override async ValueTask <ConnectState> ConnectAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken) { var socketConnector = new SocketConnector() as IConnector; var proxyEndPoint = _proxyEndPoint; ConnectState result; try { result = await socketConnector.ConnectAsync(proxyEndPoint, null, cancellationToken); if (!result.Result) { return(result); } } catch (Exception e) { return(new ConnectState { Result = false, Exception = e }); } return(await ConnectProxyAsync(remoteEndPoint, state, cancellationToken)); }
internal virtual void Update() { if (m_ClientId == -1) { return; } // don't do anything if we aren't fully connected // -> we don't check Client.Connected because then we wouldn't // process the last disconnect message. if (connectState != ConnectState.Connecting && connectState != ConnectState.Connected) { return; } // pause message handling while a scene load is in progress // // problem: // if we handle packets (calling the msgDelegates) while a // scene load is in progress, then all the handled data and state // will be lost as soon as the scene load is finished, causing // state bugs. // // solution: // don't handle messages until scene load is finished. the // transport layer will queue it automatically. if (pauseMessageHandling) { Debug.Log("NetworkClient.Update paused during scene load..."); return; } if (connectState == ConnectState.Connected) { NetworkTime.UpdateClient(this); } // any new message? // -> calling it once per frame is okay, but really why not just // process all messages and make it empty.. TransportEvent transportEvent; byte[] data; while (NetworkManager.singleton.transport.ClientGetNextMessage(out transportEvent, out data)) { switch (transportEvent) { case TransportEvent.Connected: //Debug.Log("NetworkClient loop: Connected"); if (m_Connection != null) { // reset network time stats NetworkTime.Reset(); // the handler may want to send messages to the client // thus we should set the connected state before calling the handler connectState = ConnectState.Connected; m_Connection.InvokeHandlerNoData((short)MsgType.Connect); } else { Debug.LogError("Skipped Connect message handling because m_Connection is null."); } break; case TransportEvent.Data: //Debug.Log("NetworkClient loop: Data: " + BitConverter.ToString(data)); if (m_Connection != null) { m_Connection.TransportReceive(data); } else { Debug.LogError("Skipped Data message handling because m_Connection is null."); } break; case TransportEvent.Disconnected: //Debug.Log("NetworkClient loop: Disconnected"); connectState = ConnectState.Disconnected; //GenerateDisconnectError(error); TODO which one? ClientScene.HandleClientDisconnect(m_Connection); if (m_Connection != null) { m_Connection.InvokeHandlerNoData((short)MsgType.Disconnect); } break; } } }
public void connect(string link) { connectState = ConnectState.Ready; url = link; webData = ""; }
/// <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(); } } catch (SocketException ex) { // Log exception during connection attempt OnConnectionException(ex); // If the connection is refused by the server, // keep trying until we reach our maximum connection attempts if (ex.SocketErrorCode == SocketError.ConnectionRefused && (MaxConnectionAttempts == -1 || connectState.ConnectionAttempts < MaxConnectionAttempts)) { // Server is unavailable, so keep retrying connection to the server. try { ConnectAsync(connectState); } catch { TerminateConnection(connectState.Token); } } else { // For any other reason, clean-up as if the client was disconnected. TerminateConnection(connectState.Token); } } catch (Exception ex) { // Log exception during connection attempt OnConnectionException(ex); // Terminate the connection TerminateConnection(connectState.Token); } 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(); if ((object)receiveState != null && receiveState.Token.Cancelled) receiveState.Dispose(); if ((object)sendState != null && sendState.Token.Cancelled) sendState.Dispose(); } }
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(); } }
/// <summary> /// /// </summary> public void Restart() { Connected = false; connectState = ConnectState.None; socketClient = new Socket(this.clientSettings.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); }
public Phone(Account account) { Debug.Assert(null != account, "Phone requires an Account to make calls."); this.account = account; linphone = new Linphone(); linphone.RegistrationStateChangedEvent += (Linphone.LinphoneRegistrationState state) => { switch (state) { case Linphone.LinphoneRegistrationState.LinphoneRegistrationProgress: connectState = ConnectState.Progress; break; case Linphone.LinphoneRegistrationState.LinphoneRegistrationFailed: linphone.DestroyPhone(); if (ErrorEvent != null) { ErrorEvent(null, Error.RegisterFailed); } break; case Linphone.LinphoneRegistrationState.LinphoneRegistrationCleared: connectState = ConnectState.Disconnected; if (PhoneDisconnectedEvent != null) { PhoneDisconnectedEvent(); } break; case Linphone.LinphoneRegistrationState.LinphoneRegistrationOk: connectState = ConnectState.Connected; if (PhoneConnectedEvent != null) { PhoneConnectedEvent(); } break; case Linphone.LinphoneRegistrationState.LinphoneRegistrationNone: default: break; } }; linphone.ErrorEvent += (call, message) => { Console.WriteLine("Error: {0}", message); if (ErrorEvent != null) { ErrorEvent(call, Error.UnknownError); } }; linphone.CallStateChangedEvent += (Call call) => { Call.CallState state = call.GetState(); switch (state) { case Call.CallState.Active: lineState = LineState.Busy; if (CallActiveEvent != null) { CallActiveEvent(call); } break; case Call.CallState.Loading: lineState = LineState.Busy; if (call.GetCallType() == Call.CallType.Incoming) { if (IncomingCallEvent != null) { IncomingCallEvent(call); } } break; case Call.CallState.Error: this.lineState = LineState.Free; if (ErrorEvent != null) { ErrorEvent(null, Error.CallError); } if (CallCompletedEvent != null) { CallCompletedEvent(call); } break; case Call.CallState.Completed: default: this.lineState = LineState.Free; if (CallCompletedEvent != null) { CallCompletedEvent(call); } break; } }; }
protected override async ValueTask <ConnectState> ConnectProxyAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken) { var encoding = Encoding.ASCII; var request = string.Empty; var channel = state.CreateChannel <TextPackageInfo>(new LinePipelineFilter(encoding), new ChannelOptions { ReadAsDemand = true }); channel.Start(); if (remoteEndPoint is DnsEndPoint dnsEndPoint) { request = string.Format(_requestTemplate, dnsEndPoint.Host, dnsEndPoint.Port); } else if (remoteEndPoint is IPEndPoint ipEndPoint) { request = string.Format(_requestTemplate, ipEndPoint.Address, ipEndPoint.Port); } else { return(new ConnectState { Result = false, Exception = new Exception($"The endpint type {remoteEndPoint.GetType().ToString()} is not supported.") }); } // send request await channel.SendAsync((writer) => { writer.Write(request, encoding); if (!string.IsNullOrEmpty(_username) || !string.IsNullOrEmpty(_password)) { writer.Write("Proxy-Authorization: Basic ", encoding); writer.Write(Convert.ToBase64String(encoding.GetBytes($"{_username}:{_password}")), encoding); writer.Write("\r\n\r\n", encoding); } else { writer.Write("\r\n", encoding); } }); var packStream = channel.GetPackageStream(); var p = await packStream.ReceiveAsync(); if (!HandleResponse(p, out string errorMessage)) { await channel.CloseAsync(); return(new ConnectState { Result = false, Exception = new Exception(errorMessage) }); } await channel.DetachAsync(); return(state); }
public static void Update_HubUI(ConnectState CS) { UpdateHubUI(CS); }
protected override async ValueTask <ConnectState> ConnectProxyAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken) { var channel = state.CreateChannel <Socks5Pack>(new Socks5AuthPipelineFilter(), new ChannelOptions { ReadAsDemand = true }); channel.Start(); var packStream = channel.GetPackageStream(); await channel.SendAsync(_authenHandshakeRequest); var response = await packStream.ReceiveAsync(); if (!HandleResponse(response, Socket5ResponseType.Handshake, out string errorMessage)) { await channel.CloseAsync(CloseReason.ProtocolError); return(new ConnectState { Result = false, Exception = new Exception(errorMessage) }); } if (response.Status == 0x02)// need pass auth { var passAuthenRequest = GetPassAuthenBytes(); await channel.SendAsync(passAuthenRequest); response = await packStream.ReceiveAsync(); if (!HandleResponse(response, Socket5ResponseType.AuthUserName, out errorMessage)) { await channel.CloseAsync(CloseReason.ProtocolError); return(new ConnectState { Result = false, Exception = new Exception(errorMessage) }); } } var endPointRequest = GetEndPointBytes(remoteEndPoint); await channel.SendAsync(endPointRequest); response = await packStream.ReceiveAsync(); if (!HandleResponse(response, Socket5ResponseType.AuthEndPoint, out errorMessage)) { await channel.CloseAsync(CloseReason.ProtocolError); return(new ConnectState { Result = false, Exception = new Exception(errorMessage) }); } await channel.DetachAsync(); return(state); }
internal virtual void Update() { if (m_ClientId == -1) { return; } switch (m_AsyncConnect) { case ConnectState.None: case ConnectState.Resolving: case ConnectState.Disconnected: return; case ConnectState.Failed: GenerateConnectError((int)NetworkError.DNSFailure); m_AsyncConnect = ConnectState.Disconnected; return; case ConnectState.Resolved: m_AsyncConnect = ConnectState.Connecting; ContinueConnect(); return; case ConnectState.Connecting: case ConnectState.Connected: { break; } } int numEvents = 0; NetworkEventType networkEvent; do { int connectionId; int channelId; int receivedSize; byte error; networkEvent = NetworkTransport.ReceiveFromHost(m_ClientId, out connectionId, out channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out receivedSize, out error); if (m_Connection != null) { m_Connection.lastError = (NetworkError)error; } if (networkEvent != NetworkEventType.Nothing) { if (LogFilter.logDev) { Debug.Log("Client event: host=" + m_ClientId + " event=" + networkEvent + " error=" + error); } } switch (networkEvent) { case NetworkEventType.ConnectEvent: if (LogFilter.logDebug) { Debug.Log("Client connected"); } if (error != 0) { GenerateConnectError(error); return; } m_AsyncConnect = ConnectState.Connected; m_Connection.InvokeHandlerNoData((short)MsgType.Connect); break; case NetworkEventType.DataEvent: if (error != 0) { GenerateDataError(error); return; } #if UNITY_EDITOR UnityEditor.NetworkDetailStats.IncrementStat( UnityEditor.NetworkDetailStats.NetworkDirection.Incoming, (short)MsgType.LLAPIMsg, "msg", 1); #endif // create a buffer with exactly 'receivedSize' size for the handlers so we don't need to read // a size header (saves bandwidth) byte[] data = new byte[receivedSize]; Array.Copy(m_MsgBuffer, data, receivedSize); m_Connection.TransportReceive(data, channelId); break; case NetworkEventType.DisconnectEvent: if (LogFilter.logDebug) { Debug.Log("Client disconnected"); } m_AsyncConnect = ConnectState.Disconnected; if (error != 0) { if ((NetworkError)error != NetworkError.Timeout) { GenerateDisconnectError(error); } } ClientScene.HandleClientDisconnect(m_Connection); if (m_Connection != null) { m_Connection.InvokeHandlerNoData((short)MsgType.Disconnect); } break; case NetworkEventType.Nothing: break; default: if (LogFilter.logError) { Debug.LogError("Unknown network message type received: " + networkEvent); } break; } if (++numEvents >= k_MaxEventsPerFrame) { if (LogFilter.logDebug) { Debug.Log("MaxEventsPerFrame hit (" + k_MaxEventsPerFrame + ")"); } break; } if (m_ClientId == -1) { break; } }while (networkEvent != NetworkEventType.Nothing); }
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(); } }
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); } }
/// <summary> /// /// </summary> /// <param name="e"></param> protected virtual void DoOpened(SocketEventArgs e) { connectState = ConnectState.Success; }
/// <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; }
private void DoCloseState() { Connected = false; connectState = ConnectState.Closed; }
/// <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; }
/* ===================== 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(); } }
protected override void onAsyncConnect(ConnectState state) { try { //state.socket.Connect(state.connectIP, state.connectPort); byte[] helloPacket = System.Text.Encoding.ASCII.GetBytes(UDP_HELLO); state.socket.SendTo(helloPacket, helloPacket.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(state.connectIP), state.connectPort)); ArrayList readList = new ArrayList(); readList.Add(state.socket); Socket.Select(readList, null, null, 3000000); if (readList.Count > 0) { byte[] buffer = new byte[UDP_PACKET_MAX]; int length = state.socket.Receive(buffer); if (length <= 0) { Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), failed to connect to '{0}:{1}'! receive hello-ack error!", state.connectIP, state.connectPort)); state.error = "receive hello-ack error!"; } else { MemoryStream stream = new MemoryStream(); Array.Copy(buffer, 0, stream.data(), stream.wpos, length); stream.wpos = length; string helloAck = stream.readString(); string versionString = stream.readString(); uint conv = stream.readUint32(); if (helloAck != UDP_HELLO_ACK) { Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), failed to connect to '{0}:{1}'! receive hello-ack({2}!={3}) mismatch!", state.connectIP, state.connectPort, helloAck, UDP_HELLO_ACK)); state.error = "hello-ack mismatch!"; } else if (KBEngineApp.app.serverVersion != versionString) { Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), failed to connect to '{0}:{1}'! version({2}!={3}) mismatch!", state.connectIP, state.connectPort, versionString, KBEngineApp.app.serverVersion)); state.error = "version mismatch!"; } else if (conv == 0) { Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), failed to connect to '{0}:{1}'! conv is 0!", state.connectIP, state.connectPort)); state.error = "kcp conv error!"; } ((NetworkInterfaceKCP)state.networkInterface).connID = conv; } } else { Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), connect to '{0}:{1}' timeout!'", state.connectIP, state.connectPort)); state.error = "timeout!"; } } catch (Exception e) { Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), connect to '{0}:{1}' fault! error = '{2}'", state.connectIP, state.connectPort, e)); state.error = e.ToString(); } }
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; }
private static bool CompareExchange(ref long state, ConnectState value, ConnectState comparand) { return(Interlocked.CompareExchange(ref state, (long)value, (long)comparand) == (long)comparand); }
private void HandleReceive(byte[] buffer) { if (buffer[0] == 8) { if ((Command)buffer[1] == Command.CMD_DISCONNECT) { if (requestid == 0) { } else { uint reqid = ((uint)buffer[2] << 8) + buffer[3]; if (reqid == requestid) { System.Diagnostics.Debug.Write("HandleReceive DISCONNECT\r\n"); this.State = ConnectState.DISCONNECTING; } } } if (this.State == ConnectState.CONNECTING) { if ((Command)buffer[1] == Command.CMD_RSP_CONNECT && requestid == 0) { if (buffer[4] == 1) { requestid = ((uint)buffer[2] << 8) + buffer[3]; this.State = ConnectState.CONNECTINGREMOTE; if (!CallbackSendInvoke()) { throw new SocketException((int)SocketError.ConnectionAborted); } if (logReqid == 0) logReqid = requestid; } else //if (buffer[4] == 0 || buffer[4] == 3 || buffer[4] == 4 || buffer[4] == 5) { throw new SocketException((int)SocketError.ConnectionAborted); } } return; } else if (this.State == ConnectState.WAITCONNECTINGREMOTE) { if ((Command)buffer[1] == Command.CMD_RSP_CONNECT_REMOTE && requestid != 0) { if (buffer[4] == 2) { uint reqid = ((uint)buffer[2] << 8) + buffer[3]; if (reqid == requestid) { this.State = ConnectState.CONNECTED; { for (uint id = 1; id < id_to_sendBuffer.sendEndID; ++id) { SendData(id); if (id >= 1024) break; } } } } else if (buffer[4] == 0 || buffer[4] == 3 || buffer[4] == 4) { throw new SocketException((int)SocketError.ConnectionAborted); } } else { return; } } else if (this.State == ConnectState.CONNECTED) { uint reqid = ((uint)buffer[2] << 8) + buffer[3]; if (reqid == requestid) { if ((Command)buffer[1] == Command.CMD_POST) { int beg_index = 4 + 8; uint recv_id = ((uint)buffer[4] << 24) + ((uint)buffer[5] << 16) + ((uint)buffer[6] << 8) + buffer[7]; uint pack_id = ((uint)buffer[8] << 24) + ((uint)buffer[9] << 16) + ((uint)buffer[10] << 8) + buffer[11]; id_to_sendBuffer.SetSendBeginID(recv_id); id_to_recvBuffer.SetEndID(pack_id + 1); if (id_to_recvBuffer.CanInsertID(pack_id)) { byte[] ret_buf = new byte[buffer.Length - beg_index]; Array.Copy(buffer, beg_index, ret_buf, 0, ret_buf.Length); id_to_recvBuffer.InsertData(pack_id, ret_buf); } //if (true // //requestid == logReqid && logReqid != 0 // //&& (this.sendBeginID + 1 < this.sendEndID || !id_to_recvBuffer.Empty()) // ) // System.Diagnostics.Debug.Write("HandleReceive CMD_POST" // + " req=" + requestid // + " p_recv=" + recv_id // + " id=" + pack_id // + " pack " + pack_id.ToString() + " " // + " send " + id_to_sendBuffer.sendBeginID.ToString() + " " // + id_to_sendBuffer.sendEndID.ToString() // + " recv " + id_to_recvBuffer.recvCallbackID + " " + id_to_recvBuffer.recvBeginID.ToString() + " " // + id_to_recvBuffer.recvEndID.ToString() // + "\r\n" // ); } else if ((Command)buffer[1] == Command.CMD_SYN_STATUS) { int beg_index = 4 + 8; uint recv_id = ((uint)buffer[4] << 24) + ((uint)buffer[5] << 16) + ((uint)buffer[6] << 8) + buffer[7]; uint send_id = ((uint)buffer[8] << 24) + ((uint)buffer[9] << 16) + ((uint)buffer[10] << 8) + buffer[11]; id_to_sendBuffer.SetSendBeginID(recv_id); id_to_recvBuffer.SetEndID(send_id); int id_count = (buffer.Length - beg_index) / 2; //if (true // //requestid == logReqid && logReqid != 0 // //&& (this.sendBeginID + 1 < this.sendEndID || !id_to_recvBuffer.Empty()) // ) // System.Diagnostics.Debug.Write("HandleReceive CMD_SYN_STATUS" // + " req=" + requestid // + " p_recv=" + recv_id // + " p_send=" + send_id // + " size=" + id_count.ToString() // + " send " + id_to_sendBuffer.sendBeginID.ToString() + " " // + id_to_sendBuffer.sendEndID.ToString() // + " recv " + id_to_recvBuffer.recvCallbackID + " " + id_to_recvBuffer.recvBeginID.ToString() + " " // + id_to_recvBuffer.recvEndID.ToString() // + "\r\n" // ); List<ulong> idList = new List<ulong>(); for (int index = 0; index < id_count; ++index) { ulong id = recv_id + buffer[beg_index + index * 2] * 0x100u + buffer[beg_index + index * 2 + 1]; idList.Add(id); } List<ulong> packetList = this.id_to_sendBuffer.GetDataList(idList); foreach (ulong id in packetList) { SendData(id); } //for (int index = 0; index < id_count; ++index) //{ // ulong id = recv_id + buffer[beg_index + index * 2] * 0x100u + buffer[beg_index + index * 2 + 1]; // if (id > id_to_sendBuffer.sendBeginID) // { // if (this.id_to_sendBuffer.Contains(id)) // { // if (requestid == logReqid && logReqid != 0) // System.Diagnostics.Debug.Write("HandleReceive " // + " req=" + requestid // + " send " + id.ToString() // + "\r\n" // ); // SendData(id); // } // else // { // if (requestid == logReqid && logReqid != 0) // System.Diagnostics.Debug.Write("HandleReceive MISSING" // + " req=" + requestid // + " send " + id.ToString() // + "\r\n" // ); // } // } //} } } } } if (DataCallbackRecvInvoke()) { return; } else if (this.State == ConnectState.DISCONNECTING) { CallbackRecvInvoke(); } doRecv(); }
public void BeginSendTo(byte[] sendbuffer, int size, AsyncCallback callback, object state) { if (this.State == ConnectState.END) { throw new SocketException((int)SocketError.ConnectionAborted); } Update(); lock (this) { lock (asyncCallBackSendLock) { this.asyncCallBackSend = callback; //this.callBackState = state; } byte[] buffer = new byte[size]; Array.Copy(sendbuffer, 0, buffer, 0, size); if (this.State == ConnectState.CONNECTINGREMOTE) { if (sendConnectBuffer == null) { int headerSize = 0; if (buffer[0] == 3) { headerSize = 2 + buffer[1] + 2; } else if (buffer[0] == 1) { headerSize = 1 + 4 + 2; } else if (buffer[0] == 4) { headerSize = 1 + 16 + 2; } if (headerSize < buffer.Length) { byte[] dataBuffer = new byte[buffer.Length - headerSize]; Array.Copy(buffer, headerSize, dataBuffer, 0, dataBuffer.Length); buffer = new byte[headerSize]; Array.Copy(sendbuffer, buffer, headerSize); id_to_sendBuffer.PushBack(dataBuffer); } sendConnectBuffer = buffer; } else { id_to_sendBuffer.PushBack(buffer); } this.State = ConnectState.WAITCONNECTINGREMOTE; for (int i = 0; i < 2; ++i) { byte[] sendBuffer = CreateRequestConnectData(buffer); RemoteSendto(sendBuffer, sendBuffer.Length, -1, false); } } else if (this.State == ConnectState.WAITCONNECTINGREMOTE || this.State == ConnectState.CONNECTED) { if (this.State == ConnectState.WAITCONNECTINGREMOTE) { id_to_sendBuffer.PushBack(buffer); } else if (this.State == ConnectState.CONNECTED) { ulong end_id = id_to_sendBuffer.PushBack(buffer); ulong beg_id = id_to_sendBuffer.sendBeginID; if (beg_id + 1024 >= end_id) SendData(end_id - 1); } } CallbackSendInvoke(); } }
protected abstract ValueTask <ConnectState> ConnectProxyAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken);
/* ================= 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; } }
public bool ReconnectToNewHost(string serverIp, int serverPort) { if (!NetworkClient.active) { if (LogFilter.logError) { Debug.LogError("Reconnect - NetworkClient must be active"); } return(false); } if (m_Connection == null) { if (LogFilter.logError) { Debug.LogError("Reconnect - no old connection exists"); } return(false); } if (LogFilter.logInfo) { Debug.Log("NetworkClient Reconnect " + serverIp + ":" + serverPort); } ClientScene.HandleClientDisconnect(m_Connection); ClientScene.ClearLocalPlayers(); m_Connection.Disconnect(); m_Connection = null; m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); string hostnameOrIp = serverIp; m_ServerPort = serverPort; //TODO: relay reconnect /* * if (Match.NetworkMatch.matchSingleton != null) * { * hostnameOrIp = Match.NetworkMatch.matchSingleton.address; * m_ServerPort = Match.NetworkMatch.matchSingleton.port; * }*/ if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) { m_ServerIp = hostnameOrIp; m_AsyncConnect = ConnectState.Resolved; } else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost")) { m_ServerIp = "127.0.0.1"; m_AsyncConnect = ConnectState.Resolved; } else { if (LogFilter.logDebug) { Debug.Log("Async DNS START:" + hostnameOrIp); } m_AsyncConnect = ConnectState.Resolving; Dns.BeginGetHostAddresses(hostnameOrIp, new AsyncCallback(GetHostAddressesCallback), this); } return(true); }
void ConnectionlessPacket(Net.Packet packet) { string s = packet.Buffer.ReadString(); string[] tokens = Commands.TokenizeString(s); Common.Instance.WriteLine("CL Packet: {0}:{1}: {2}", packet.Address.Address, packet.Address.Port, s); string c = tokens[0]; if (c.Equals("challengeResponse")) { if (state != ConnectState.CONNECTING) { Common.Instance.WriteLine("Unwanted challenge response recieved. Ignored."); return; } if (!IPAddress.Equals(clc.serverAddress.Address, packet.Address.Address)) { // This challenge response is not coming from the expected address. // Check whether we have a matching client challenge to prevent // connection hi-jacking. c = tokens[2]; if (!int.Parse(c).Equals(clc.challenge)) { Common.Instance.WriteLine("Challenge response recieved from unexpected source. Ignored."); return; } } // start sending challenge response instead of challenge request packets clc.challenge = int.Parse(tokens[1]); state = ConnectState.CHALLENGING; clc.connectPacketCount = 0; clc.connectTime = -99999; // take this address as the new server address. This allows // a server proxy to hand off connections to multiple servers clc.serverAddress = packet.Address; Common.Instance.WriteLine("Challenge response: {0}", clc.challenge); return; } // server connection if (c.Equals("connectResponse")) { if ((int)state >= (int)ConnectState.CONNECTED) { Common.Instance.WriteLine("Duplicate connect recieved. Ignored"); return; } if (state != ConnectState.CHALLENGING) { Common.Instance.WriteLine("connectResponse packet while not connecting. Ignored."); return; } if (!IPAddress.Equals(packet.Address.Address, clc.serverAddress.Address)) { Common.Instance.WriteLine("connectResponse from wrong address. Ignored"); } clc.netchan = Net.Instance.NetChan_Setup(Net.NetSource.CLIENT, packet.Address, CVars.Instance.VariableIntegerValue("net_qport")); Net.Instance.ClientConnect(packet.Address); state = ConnectState.CONNECTED; clc.lastPacketSentTime = -99999; // send first packet immediately return; } if (c.Equals("print")) { s = tokens[1]; clc.serverMessage = s; Common.Instance.WriteLine(s); return; } Common.Instance.WriteLine("Unknown connectionless packet: {0}" + s); }
public bool ReconnectToNewHost(EndPoint secureTunnelEndPoint) { if (!NetworkClient.active) { if (LogFilter.logError) { Debug.LogError("Reconnect - NetworkClient must be active"); } return(false); } if (m_Connection == null) { if (LogFilter.logError) { Debug.LogError("Reconnect - no old connection exists"); } return(false); } if (LogFilter.logInfo) { Debug.Log("NetworkClient Reconnect to remoteSockAddr"); } ClientScene.HandleClientDisconnect(m_Connection); ClientScene.ClearLocalPlayers(); m_Connection.Disconnect(); m_Connection = null; m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); if (secureTunnelEndPoint == null) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: null endpoint passed in"); } m_AsyncConnect = ConnectState.Failed; return(false); } // Make sure it's either IPv4 or IPv6 if (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork && secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6"); } m_AsyncConnect = ConnectState.Failed; return(false); } // Make sure it's an Endpoint we know what to do with string endPointType = secureTunnelEndPoint.GetType().FullName; if (endPointType == "System.Net.IPEndPoint") { IPEndPoint tmp = (IPEndPoint)secureTunnelEndPoint; Connect(tmp.Address.ToString(), tmp.Port); return(m_AsyncConnect != ConnectState.Failed); } if ((endPointType != "UnityEngine.XboxOne.XboxOneEndPoint") && (endPointType != "UnityEngine.PS4.SceEndPoint")) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint or SceEndPoint)"); } m_AsyncConnect = ConnectState.Failed; return(false); } byte error = 0; // regular non-relay connect m_RemoteEndPoint = secureTunnelEndPoint; m_AsyncConnect = ConnectState.Connecting; try { m_ClientConnectionId = NetworkTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out error); } catch (Exception ex) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: Exception when trying to connect to EndPoint: " + ex); } m_AsyncConnect = ConnectState.Failed; return(false); } if (m_ClientConnectionId == 0) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: Unable to connect to EndPoint (" + error + ")"); } m_AsyncConnect = ConnectState.Failed; return(false); } m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); m_Connection.SetHandlers(m_MessageHandlers); m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology); return(true); }
public void BeginConnect(string method, string password, IPEndPoint ep, string proxyServerURI, int proxyServerPort, AsyncCallback callback, Object state) { if (this.State == ConnectState.END) { throw new SocketException((int)SocketError.ConnectionAborted); } Update(); { if (this.State == ConnectState.READY) { encryptMethod = method; encryptPassword = password; this.encryptor = EncryptorFactory.GetEncryptor(method, password); this.decryptor = EncryptorFactory.GetEncryptor(method, password); this.sockEndPoint = ep; this.proxyServerURI = proxyServerURI; this.proxyServerPort = proxyServerPort; sock = new Socket(ep.AddressFamily, SocketType.Dgram, ProtocolType.Udp); sock.SendBufferSize = 1024 * 1024 * 4; sock.ReceiveBufferSize = 1024 * 1024 * 4; random.NextBytes(localid); byte[] sendBuffer = CreateConnectData(); lock (asyncCallBackSendLock) { this.asyncCallBackSend = callback; //this.callBackState = state; } RemoteSendto(sendBuffer, sendBuffer.Length, -1, false); doRecv(); this.State = ConnectState.CONNECTING; } } }
public void Connect(EndPoint secureTunnelEndPoint) { bool usePlatformSpecificProtocols = NetworkTransport.DoesEndPointUsePlatformProtocols(secureTunnelEndPoint); PrepareForConnect(usePlatformSpecificProtocols); if (LogFilter.logDebug) { Debug.Log("Client Connect to remoteSockAddr"); } if (secureTunnelEndPoint == null) { if (LogFilter.logError) { Debug.LogError("Connect failed: null endpoint passed in"); } m_AsyncConnect = ConnectState.Failed; return; } // Make sure it's either IPv4 or IPv6 if (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork && secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6) { if (LogFilter.logError) { Debug.LogError("Connect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6"); } m_AsyncConnect = ConnectState.Failed; return; } // Make sure it's an Endpoint we know what to do with string endPointType = secureTunnelEndPoint.GetType().FullName; if (endPointType == "System.Net.IPEndPoint") { IPEndPoint tmp = (IPEndPoint)secureTunnelEndPoint; Connect(tmp.Address.ToString(), tmp.Port); return; } if ((endPointType != "UnityEngine.XboxOne.XboxOneEndPoint") && (endPointType != "UnityEngine.PS4.SceEndPoint") && (endPointType != "UnityEngine.PSVita.SceEndPoint")) { if (LogFilter.logError) { Debug.LogError("Connect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint or SceEndPoint)"); } m_AsyncConnect = ConnectState.Failed; return; } byte error = 0; // regular non-relay connect m_RemoteEndPoint = secureTunnelEndPoint; m_AsyncConnect = ConnectState.Connecting; try { m_ClientConnectionId = NetworkTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out error); } catch (Exception ex) { if (LogFilter.logError) { Debug.LogError("Connect failed: Exception when trying to connect to EndPoint: " + ex); } m_AsyncConnect = ConnectState.Failed; return; } if (m_ClientConnectionId == 0) { if (LogFilter.logError) { Debug.LogError("Connect failed: Unable to connect to EndPoint (" + error + ")"); } m_AsyncConnect = ConnectState.Failed; return; } m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); m_Connection.SetHandlers(m_MessageHandlers); m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology); }
public void Close() { lock (this) { if (this.State == ConnectState.END) { return; } else { this.State = ConnectState.END; } } sendBufferList = new LinkedList<byte[]>(); lock (encryptionLock) { lock (decryptionLock) { if (encryptor != null) ((IDisposable)encryptor).Dispose(); if (decryptor != null) ((IDisposable)decryptor).Dispose(); } } CallbackSendInvoke(); CallbackRecvInvoke(); lock (this) { if (sock != null) { try { sock.Shutdown(SocketShutdown.Both); sock.Close(); } catch (Exception e) { Logging.LogUsefulException(e); } sock = null; } } id_to_sendBuffer = new SendQueue(); id_to_recvBuffer = new RecvQueue(); }
internal virtual void Update() { if (m_ClientId == -1) { return; } switch (m_AsyncConnect) { case ConnectState.None: case ConnectState.Resolving: case ConnectState.Disconnected: return; case ConnectState.Failed: GenerateConnectError((int)NetworkError.DNSFailure); m_AsyncConnect = ConnectState.Disconnected; return; case ConnectState.Resolved: m_AsyncConnect = ConnectState.Connecting; ContinueConnect(); return; case ConnectState.Connecting: case ConnectState.Connected: { break; } } if (m_Connection != null) { if ((int)Time.time != m_StatResetTime) { m_Connection.ResetStats(); m_StatResetTime = (int)Time.time; } } int numEvents = 0; NetworkEventType networkEvent; do { int connectionId; int channelId; int receivedSize; byte error; networkEvent = NetworkTransport.ReceiveFromHost(m_ClientId, out connectionId, out channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out receivedSize, out error); if (m_Connection != null) { m_Connection.lastError = (NetworkError)error; } if (networkEvent != NetworkEventType.Nothing) { if (LogFilter.logDev) { Debug.Log("Client event: host=" + m_ClientId + " event=" + networkEvent + " error=" + error); } } switch (networkEvent) { case NetworkEventType.ConnectEvent: if (LogFilter.logDebug) { Debug.Log("Client connected"); } if (error != 0) { GenerateConnectError(error); return; } m_AsyncConnect = ConnectState.Connected; m_Connection.InvokeHandlerNoData(MsgType.Connect); break; case NetworkEventType.DataEvent: if (error != 0) { GenerateDataError(error); return; } #if UNITY_EDITOR UnityEditor.NetworkDetailStats.IncrementStat( UnityEditor.NetworkDetailStats.NetworkDirection.Incoming, MsgType.LLAPIMsg, "msg", 1); #endif m_MsgReader.SeekZero(); m_Connection.TransportReceive(m_MsgBuffer, receivedSize, channelId); break; case NetworkEventType.DisconnectEvent: if (LogFilter.logDebug) { Debug.Log("Client disconnected"); } m_AsyncConnect = ConnectState.Disconnected; if (error != 0) { if ((NetworkError)error != NetworkError.Timeout) { GenerateDisconnectError(error); } } ClientScene.HandleClientDisconnect(m_Connection); if (m_Connection != null) { m_Connection.InvokeHandlerNoData(MsgType.Disconnect); } break; case NetworkEventType.Nothing: break; default: if (LogFilter.logError) { Debug.LogError("Unknown network message type received: " + networkEvent); } break; } if (++numEvents >= k_MaxEventsPerFrame) { if (LogFilter.logDebug) { Debug.Log("MaxEventsPerFrame hit (" + k_MaxEventsPerFrame + ")"); } break; } if (m_ClientId == -1) { break; } }while (networkEvent != NetworkEventType.Nothing); if (m_Connection != null && m_AsyncConnect == ConnectState.Connected) { m_Connection.FlushChannels(); } }
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); } }
public void Connect(EndPoint secureTunnelEndPoint) { bool usePlatformSpecificProtocols = NetworkTransport.DoesEndPointUsePlatformProtocols(secureTunnelEndPoint); this.PrepareForConnect(usePlatformSpecificProtocols); if (LogFilter.logDebug) { Debug.Log("Client Connect to remoteSockAddr"); } if (secureTunnelEndPoint == null) { if (LogFilter.logError) { Debug.LogError("Connect failed: null endpoint passed in"); } this.m_AsyncConnect = ConnectState.Failed; } else if ((secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork) && (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6)) { if (LogFilter.logError) { Debug.LogError("Connect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6"); } this.m_AsyncConnect = ConnectState.Failed; } else { string fullName = secureTunnelEndPoint.GetType().FullName; if (fullName == "System.Net.IPEndPoint") { IPEndPoint point = (IPEndPoint)secureTunnelEndPoint; this.Connect(point.Address.ToString(), point.Port); } else if (((fullName != "UnityEngine.XboxOne.XboxOneEndPoint") && (fullName != "UnityEngine.PS4.SceEndPoint")) && (fullName != "UnityEngine.PSVita.SceEndPoint")) { if (LogFilter.logError) { Debug.LogError("Connect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint or SceEndPoint)"); } this.m_AsyncConnect = ConnectState.Failed; } else { byte error = 0; this.m_RemoteEndPoint = secureTunnelEndPoint; this.m_AsyncConnect = ConnectState.Connecting; try { this.m_ClientConnectionId = NetworkTransport.ConnectEndPoint(this.m_ClientId, this.m_RemoteEndPoint, 0, out error); } catch (Exception exception) { if (LogFilter.logError) { Debug.LogError("Connect failed: Exception when trying to connect to EndPoint: " + exception); } this.m_AsyncConnect = ConnectState.Failed; return; } if (this.m_ClientConnectionId == 0) { if (LogFilter.logError) { Debug.LogError("Connect failed: Unable to connect to EndPoint (" + error + ")"); } this.m_AsyncConnect = ConnectState.Failed; } else { this.m_Connection = (NetworkConnection)Activator.CreateInstance(this.m_NetworkConnectionClass); this.m_Connection.SetHandlers(this.m_MessageHandlers); this.m_Connection.Initialize(this.m_ServerIp, this.m_ClientId, this.m_ClientConnectionId, this.m_HostTopology); } } } }
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); } } }
void OnFightStateChange(ConnectState state, string message) { Util.CallMethod("ConnectionManager", "OnStateChanged", fightConn, state, message); }
private void ConnectCallback(IAsyncResult ar) { if (closed) { return; } try { // Complete the connection. if (remoteTDP == null || socks5RemotePort != 0) { remote.EndConnect(ar); } else { remoteTDP.EndConnect(ar); } if (socks5RemotePort > 0) { if (ConnectProxyServer(server.server, server.server_port, remote, (int)SocketError.ConnectionReset)) { if (server.tcp_over_udp && remoteTDP != null) { remoteTDP.BeginConnect(server.method, server.password, remoteUDPEndPoint, server.server, server.server_port, new AsyncCallback(ConnectTDPCallback), null); return; } } else { throw new SocketException((int)SocketError.ConnectionReset); } } speedTester.EndConnect(); server.ServerSpeedLog().AddConnectTime((int)(speedTester.timeConnectEnd - speedTester.timeConnectBegin).TotalMilliseconds); //Console.WriteLine("Socket connected to {0}", // remote.RemoteEndPoint.ToString()); 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(); } }
protected abstract void onAsyncConnect(ConnectState state);
/// <summary> /// Releases the unmanaged resources used by the <see cref="TcpClient"/> and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if ((object)m_connectState != null) { TerminateConnection(m_connectState.Token); m_connectState.Dispose(); m_connectState = null; } if ((object)m_receiveState != null) { m_receiveState.Dispose(); m_receiveState = null; } if ((object)m_sendState != null) { m_sendState.Dispose(); m_sendState = null; } if ((object)m_connectWaitHandle != null) { m_connectWaitHandle.Set(); m_connectWaitHandle.Dispose(); m_connectWaitHandle = null; } } } finally { m_disposed = true; // Prevent duplicate dispose. base.Dispose(disposing); // Call base class Dispose(). } } }
/// <summary> /// 在非主线程执行:连接服务器 /// </summary> private void _asyncConnect(ConnectState state) { Dbg.DEBUG_MSG(string.Format("NetworkInterfaceBase::_asyncConnect(), will connect to '{0}:{1}' ...", state.connectIP, state.connectPort)); onAsyncConnect(state); }
/// <summary> /// Initiates an asynchronous connection attempt. /// </summary> private void ConnectAsync(ConnectState connectState) { if (!connectState.Token.Cancelled) { if (!connectState.Socket.ConnectAsync(connectState.ConnectArgs)) ThreadPool.QueueUserWorkItem(state => ProcessConnect(connectState)); } }
protected virtual void onAsyncConnectCB(ConnectState state) { }
/// <summary> /// Cleans up any connection-related objects when the connection is no longer needed /// (either closed intentionally or encounters an exception) /// </summary> /// <param name="state">The <see cref="ConnectState"/> state information</param> private void CleanUpSocket(ConnectState state) { try { if (state != null) { if (connecting.ContainsKey(state.GUID)) connecting.Remove(state.GUID); if (reading.ContainsKey(state.GUID)) reading.Remove(state.GUID); if (state.Request != null) { state.Request.Abort(); } ResponseState responseState = state as ResponseState; if (responseState != null) { if (responseState.Stream != null) { responseState.Stream.Close(); } responseState.Stream = null; } state.Request = null; } } catch { Utility.WriteDebugInfo("CometClient cleanup socket failed"); } state = null; }
/// <summary> /// 收到蓝牙消息 /// </summary> /// <param name="message"></param> public void ReceiveBluetoothMessage(string message) { Debug.Log("ReceiveBluetoothMessage message " + message); var jsonData = JsonMapper.ToObject(message); if (jsonData.Keys.Contains("status")) { var status = (int)jsonData["status"]; var data = jsonData["data"]; switch (status) { case BLUETOOTH_SCAN_DEVICE: if (null != OnGetDeviceInfoEvent) { //Debug.Log("扫描到设备 " + data); OnGetDeviceInfoEvent.Invoke(data); } break; case BLUETOOTH_SERVICE_DISCOVERED: //BLUETOOTH_CONNECTED只是连接成功 BLUETOOTH_SERVICE_DISCOVERED才是真正的可以正常通讯了 IsConnected = true; startTime = -1f; //连接成功的时候才停止计时 ConnectedState = ConnectState.Connected; if (null != OnConnectedSuccessedEvent) { //Debug.Log("蓝牙连接成功 "); OnConnectedSuccessedEvent.Invoke(); } break; case BLUETOOTH_DISCONNECTED: //避免无限断开的提示 if (ConnectedState != ConnectState.DisConnected) { ConnectedState = ConnectState.DisConnected; if (!IsConnected) { startTime = -1f; //连接失败的时候才停止计时 //当前未连接则为连接失败 if (null != OnConnectedFailedEvent) { //Debug.Log("蓝牙连接失败 "); OnConnectedFailedEvent.Invoke(); } } else { //当前已连接则为断开连接 IsConnected = false; if (null != OnDisconnectedEvent) { //Debug.Log("蓝牙连接断开 "); OnDisconnectedEvent.Invoke(); } } } break; case BLUETOOTH_VALUE_CHANGED: if (data[0].Keys.Contains("key")) { var key = data[0]["key"].ToString(); //Debug.Log("蓝牙消息 key " + key); if (key.Equals("B2DOWN")) { if (null != OnShootDownEvent) { OnShootDownEvent.Invoke(); } } else if (key.Equals("B2UP")) { if (null != OnShootUpEvent) { OnShootUpEvent.Invoke(); } } else if (key.Equals("B3DOWN")) { //装子弹 if (null != OnSmoothDownEvent) { OnSmoothDownEvent.Invoke(); } } else if (key.Equals("B3UP")) { if (null != OnSmoothUpEvent) { OnSmoothUpEvent.Invoke(); } } else if (key.Equals("B4DOWN")) { if (null != OnActionDownEvent) { OnActionDownEvent.Invoke(); } } else if (key.Equals("B4UP")) { if (null != OnActionUpEvent) { OnActionUpEvent.Invoke(); } } } break; case BLUETOOTH_RECONNECT: //重连 ConnectedState = ConnectState.ReConnecting; startTime = Time.time; if (null != OnReconnectingEvent) { //Debug.Log("蓝牙重连中 "); OnReconnectingEvent.Invoke(); } break; case PERMISSION_GRANTED: //用户授权蓝牙的时候点了允许 GrantedState = PERMISSION_GRANTED; IsGranted = true; if (null != OnGrantedSuccessedEvent) { //Debug.Log("用户授权蓝牙的时候点了允许"); OnGrantedSuccessedEvent.Invoke(); } break; case PERMISSION_DENIED: //用户授权蓝牙的时候点了拒绝 GrantedState = PERMISSION_DENIED; IsGranted = false; if (null != OnGrantedFailedEvent) { //Debug.Log("用户授权蓝牙的时候点了拒绝 "); OnGrantedFailedEvent.Invoke(); } break; case PERMISSION_DENIED_NEVER: //用户授权蓝牙的时候点了拒绝不再提醒 GrantedState = PERMISSION_DENIED_NEVER; IsGranted = false; if (null != OnGrantedNeverEvent) { //Debug.Log("用户授权蓝牙的时候点了拒绝不再提醒 "); OnGrantedNeverEvent.Invoke(); } break; case BLUETOOTH_DISENABLED: //没有启用蓝牙 #if UNITY_IPHONE isOpenedIOS = false; #endif if (null != OnEnabledFailedEvent) { //Debug.Log("没有启用蓝牙 "); OnEnabledFailedEvent.Invoke(); } break; case BLUETOOTH_ENABLED: //Debug.Log("开启了蓝牙 请求权限 "); //开启了蓝牙 #if UNITY_ANDROID RequestPermission(); if (null != OnEnabledSuccessedEvent) { OnEnabledSuccessedEvent.Invoke(); } #elif UNITY_IPHONE isOpenedIOS = true; if (null != OnGrantedSuccessedEvent) { Debug.Log("ios 开启了蓝牙"); OnGrantedSuccessedEvent.Invoke(); } #endif break; default: //Debug.LogError("其它消息类型 status " + status); break; } } }
public void Start() { Utility.WriteDebugInfo("Comet Client Starting"); ConnectState state = null; try { if (!this.isWaiting) { lock (this.locker) { if (!this.isWaiting) { // well, we arent really waiting yet, but the connecting is considered part of it // since another attempt should not be made while we are trying this attempt this.isWaiting = true; // dont reconnect too quickly or it causes HttpWebRequest exceptions DateTime now = DateTime.Now; if (now < this.nextReconnectTime) { int wait = (this.nextReconnectTime - now).Milliseconds; System.Threading.Thread.Sleep(wait); } // build HTTP request HttpWebRequest request = null; // this handles cases where the url is not only malformed, but unacceptable to HttpWebRequest (not http or https, for example) // in these cases, we dont want to fire OnDisconnected because clients that are set to auto-reconnect will end up in an endless loop try { request = (HttpWebRequest)WebRequest.Create(this.url); } catch { OnInvalidUrl(); return; } request.AllowWriteStreamBuffering = false; request.Pipelined = true; state = new ConnectState(request); connecting.Add(state.GUID, state); request.Method = "GET"; request.UserAgent = "notify.io Windows Client"; request.Timeout = this.autoResetInterval; // deal with a bug request.KeepAlive = false; request.ServicePoint.MaxIdleTime = this.reconnectDelay * 1000; Utility.WriteDebugInfo("CometClient waiting: TRUE"); HttpWebRequestHelper hwrh = new HttpWebRequestHelper(request); hwrh.GetResponseAsync(ConnectCallback, state); this.OnConnected(); } else { //Utility.WriteLine("already connecting 2"); } } } else { //Utility.WriteLine("already connecting 1"); } } catch { //Utility.WriteLine("EXCEPTION - CometClient.Start"); // suppress OnDisconnected(); } }
public bool Init() { connectState = ConnectState.None; return(true); }