public void SendMessage(PiranhaMessage message) { ClientConnectionState state = this.m_connection.State; if (state != ClientConnectionState.LOGGED) { if (state == ClientConnectionState.DISCONNECTED) { return; } int messageType = message.GetMessageType(); if (messageType != LoginFailedMessage.MESSAGE_TYPE && messageType != LoginOkMessage.MESSAGE_TYPE && messageType != UnlockAccountFailedMessage.MESSAGE_TYPE && messageType != UnlockAccountOkMessage.MESSAGE_TYPE) { return; } if (messageType == LoginFailedMessage.MESSAGE_TYPE) { this.m_connection.SetState(ClientConnectionState.LOGIN_FAILED); } } this.m_connection.Messaging.Send(message); }
private void OnConnectStateChanged(ClientConnectionState state) { switch (state) { case ClientConnectionState.NotConnecting: SetDisconnected(); _connectingHud?.ShowMessage($"Error:\n{_baseClient.LastDisconnectReason ?? "Not connecting."}"); break; case ClientConnectionState.ResolvingHost: _connectingHud?.ShowMessage("Connecting...\nResolving host."); break; case ClientConnectionState.EstablishingConnection: _connectingHud?.ShowMessage("Connecting...\nEstablishing connection."); break; case ClientConnectionState.Handshake: _connectingHud?.ShowMessage("Connecting...\nPerforming handshake."); break; case ClientConnectionState.Connected: _connectingHud?.ShowMessage("Connected to the server."); break; } }
public override void ConnectToServer(IPAddress ipAddress, int port, Action <uint> onClientConnectedCallback = null) { this.onClientConnectedCallback = onClientConnectedCallback; UdpNetworkManager.Instance.StartClient(ipAddress, port); saltGeneratedByClient = GenerateSalt(); clientConnectionState = ClientConnectionState.RequestingConnection; }
/// <inheritdoc /> public void Shutdown(string reason) { foreach (var kvChannel in _channels) { DisconnectChannel(kvChannel.Value, reason); } // request shutdown of the netPeer _netPeers.ForEach(p => p.Shutdown(reason)); _netPeers.Clear(); // wait for the network thread to finish its work (like flushing packets and gracefully disconnecting) // Lidgren does not expose the thread, so we can't join or or anything // pretty much have to poll every so often and wait for it to finish before continuing // when the network thread is finished, it will change status from ShutdownRequested to NotRunning while (_netPeers.Any(p => p.Status == NetPeerStatus.ShutdownRequested)) { // sleep the thread for an arbitrary length so it isn't spinning in the while loop as much Thread.Sleep(50); } _strings.Reset(); _cancelConnectTokenSource?.Cancel(); _clientConnectionState = ClientConnectionState.NotConnecting; }
public void SetState(ClientConnectionState state) { if (this.State != ClientConnectionState.DISCONNECTED) { this.State = state; } }
private void OnConnectStateChanged(ClientConnectionState state) { if (state != ClientConnectionState.Connected) { return; } var path = new ResourcePath($"/rules_last_seen_{_configManager.GetCVar(CCVars.ServerId)}"); var showRules = true; if (_resource.UserData.TryReadAllText(path, out var lastReadTimeText) && DateTime.TryParse(lastReadTimeText, null, DateTimeStyles.AssumeUniversal, out var lastReadTime)) { showRules = lastReadTime < DateTime.UtcNow - TimeSpan.FromDays(60); } else { SaveLastReadTime(); } if (showRules) { OpenRulesAndInfoWindow?.Invoke(); } }
private void OnConnectionAccepted() { if (!isServer && clientConnectionState == ClientConnectionState.OnChallengeResponse) { Debug.Log("OnConnectionAccepted"); clientConnectionState = ClientConnectionState.OnConnectionAccepted; } }
protected Processor(DbController controller, string hostString) { this.hostString = hostString; dbInterfaces = new Dictionary <string, DatabaseInterface>(); this.controller = controller; state = 0; authenticationTries = 0; dbCallback = OnDatabaseEvent; }
protected Processor(DbController controller, string hostString) { this.hostString = hostString; dbInterfaces = new Dictionary<string, DatabaseInterface>(); this.controller = controller; state = 0; authenticationTries = 0; dbCallback = OnDatabaseEvent; }
public void ChangeClientState(ClientConnectionState state) { if (CurrentState != state && state == ClientConnectionState.READY) { ClientReady?.Invoke(this, EventArgs.Empty); } CurrentState = state; Console.WriteLine($"Client {ToString()} state changed to ({state.ToString()})"); }
internal Client(TcpClient clientSocket, IPAddress ip, DataBuffer clientBuffer) { _socket = clientSocket; IP = ip; Buffer = clientBuffer; _currentConnectionState = ClientConnectionState.Connected; lock (_L_activeClients) { ++TotalClients; ++ActiveClients; } }
// ---------- Primitive _queries ---------- private byte [] ChangeDatabase(int dispatchId, byte[] command) { // Read the query from the Query. MemoryStream input = new MemoryStream(command, 8, command.Length - 8); BinaryReader reader = new BinaryReader(input, Encoding.Unicode); string databaseName = reader.ReadString(); try { dbInterface.ChangeDatabase(databaseName); state = ClientConnectionState.NotAuthenticated; return(SimpleSuccess(dispatchId)); } catch (DataException e) { return(Exception(dispatchId, e)); } }
public static void Run(IAsyncResult result) { Logger.Log("start AcceptTcpClient.Run"); if (result.IsCompleted == false || !(result.AsyncState is TcpListener)) { return; } Logger.Log("load state"); var tcpListener = result.AsyncState as TcpListener; try { Logger.Log("tcpListener.EndAcceptTcpClient"); var tcpClient = tcpListener.EndAcceptTcpClient(result); tcpClient.ReceiveBufferSize = Globals.BufferSize; tcpClient.SendBufferSize = Globals.BufferSize; Logger.Log("tcpClient.GetStream"); var clientStream = tcpClient.GetStream(); Logger.Log("new ClientConnectionState"); var state = new ClientConnectionState { Session = new RequestSession(), Client = tcpClient, ClientStream = clientStream, ClientStreamBase = clientStream, Buffer = new byte[Globals.BufferSize], MessageStream = new MemoryStream(), IsSsl = false }; Logger.Log("clientStream.BeginRead"); clientStream.BeginRead(state.Buffer, 0, state.Buffer.Length, ReadFromClient.Run, state); } catch (Exception ex) { Logger.Log("Error while attempting to complete async connection."); Logger.Log(ex); } // auf den nächsten Client warten und reagieren Logger.Log("tcpListener.BeginAcceptTcpClient"); tcpListener.BeginAcceptTcpClient(AcceptTcpClient.Run, tcpListener); Logger.Log("end AcceptTcpClient.Run"); }
public void Poll() { if (State != ClientConnectionState.Started) return; var status = ""; try { var wc = new WebClient(); status = wc.DownloadString(Utilities.CombineURL(_cfg.ManagerUrl, "/job/" + JobId + "/status")).ToLower(); } catch (Exception z) { } if (status == "done") { Console.WriteLine("Job " + JobId + " is now done."); State = ClientConnectionState.Done; } else if (status != "working") Console.WriteLine("Unknown job status: " + status); }
public void Disconnect(bool sendToServer, string reason = "Client disconnected") { if ((int)CurrentState % 5 != 0) { CurrentState = ClientConnectionState.DISCONNECTED; } else { return; } try { if (sendToServer) { Write(GetDisconnectPacket(reason)); } } catch (Exception) { } try { if (Client.Client.Connected) { Client.Close(); } } catch (Exception) { } ConnectionDisconnected?.Invoke(this, new ConnectionDisconnectedEventArgs() { Reason = reason, Client = this, }); }
/// <summary> /// Connect to the specified <see cref="IPEndPoint"/> /// </summary> /// <param name="endpoint"></param> public void Connect(Server server) { if ((int)CurrentState % 5 != 0) { Disconnect(true); } Client = new TcpClient(); CurrentServer = server; CurrentState = ClientConnectionState.CONNECTED; try { Client.Connect(server.Address, server.Port); } catch (Exception) { Disconnect(false, "Failed to connect to server"); throw; } if (ListenThread != null) { ListenThread.Abort(); } ListenThread = new Thread(ReadLoop) { IsBackground = true, Name = "Network Listener", }; ListenThread.Start(); Connected?.Invoke(this, EventArgs.Empty); }
private void ConnectionStateChanged(ClientConnectionState state) { ConnectStatus.Text = Loc.GetString($"connecting-state-{state}"); }
private void HandlePacket(byte type, byte[] payload) { List <byte> payloadList = new List <byte>(payload); switch (type) { case (byte)SCPackets.QUERY: if ((int)CurrentState % 8 == 0) { break; } int nameLength = payloadList.GetNextInt(); string name = Encoding.Unicode.GetString(payloadList.GetBytes(nameLength)); int maxOnline = payloadList.GetNextInt(); int online = payloadList.GetNextInt(); CurrentServer.Name = name; CurrentServer.MaxOnline = maxOnline; CurrentServer.Online = online; CurrentServer.Status = ServerStatus.ONLINE; ServerQueryReceived?.Invoke(this, new ServerQueryReceivedEventArgs() { Server = CurrentServer, Client = this }); break; case (byte)SCPackets.MESSAGE: if (CurrentState != ClientConnectionState.READY) { break; } bool broadcast = BitConverter.ToBoolean(payloadList.GetByteInByteCollection().CheckEndianness(), 0); int authorLength = payloadList.GetNextInt(); string author = Encoding.Unicode.GetString(payloadList.GetBytes(authorLength)); int messageLength = payloadList.GetNextInt(); string message = Encoding.Unicode.GetString(payloadList.GetBytes(messageLength)); SendMessage( (broadcast) ? MessageType.BROADCAST : MessageType.CHAT, message, author); break; case (byte)SCPackets.READY: if (CurrentState != ClientConnectionState.CONNECTED) { break; } CurrentState = ClientConnectionState.READY; ClientReady?.Invoke(this, EventArgs.Empty); break; case (byte)SCPackets.NOTIFICATION: if (CurrentState != ClientConnectionState.READY) { break; } MessageBoxIcon[] iconMap = new MessageBoxIcon[] { MessageBoxIcon.None, MessageBoxIcon.Information, MessageBoxIcon.Warning, MessageBoxIcon.Error, }; int level = payloadList.GetNextInt(); int contentLength = payloadList.GetNextInt(); string content = Encoding.Unicode.GetString(payloadList.GetBytes(contentLength)); if (level > 4) // invalid level { break; } SendMessage(new MessageEventArgs() { Content = content, Type = MessageType.NOTIFICATION, NotificationIcon = iconMap[level], Client = this, }); break; case (byte)SCPackets.DISCONNECT: Disconnect(false, "Server closed connection."); break; default: break; } }
public NetClient(string username) { Username = username; CurrentState = ClientConnectionState.DISCONNECTED; }
/// <summary> /// Processes a single Query from the client. /// </summary> /// <param name="command"></param> /// <returns> /// Returns a byte array and the response is written out as a byte array, or /// <b>null</b> if the connection has been closed. /// </returns> protected byte[] ProcessCommand(byte[] command) { if (state == ClientConnectionState.Closed) { // State 0 means we looking for the header... BinaryReader reader = new BinaryReader(new MemoryStream(command), Encoding.ASCII); /* * int magic = ByteBuffer.ReadInt4(Query, 0); * // The driver version number * int maj_ver = ByteBuffer.ReadInt4(Query, 4); * int min_ver = ByteBuffer.ReadInt4(Query, 8); */ reader.ReadInt32(); // magic reader.ReadInt32(); // server major version reader.ReadInt32(); // server minor version string databaseName = reader.ReadString(); if (!ChangeDatabaseInterface(controller.Config, databaseName)) { return(Single(ProtocolConstants.DatabaseNotFound)); } Version version = Assembly.GetExecutingAssembly().GetName().Version; byte[] ackCommand = new byte[4 + 1 + 4 + 4 + 1]; // Send back an acknowledgement and the version number of the server ByteBuffer.WriteInteger(ProtocolConstants.Acknowledgement, ackCommand, 0); ackCommand[4] = 1; ByteBuffer.WriteInteger(version.Major, ackCommand, 5); ByteBuffer.WriteInteger(version.Minor, ackCommand, 9); ackCommand[13] = 0; // Set to the next state. state = ClientConnectionState.NotAuthenticated; // Return the acknowledgement return(ackCommand); } if (state == ClientConnectionState.NotAuthenticated) { // State 4 means we looking for username and password... MemoryStream input = new MemoryStream(command); BinaryReader reader = new BinaryReader(input, Encoding.ASCII); string defaultSchema = reader.ReadString(); string username = reader.ReadString(); string password = reader.ReadString(); try { if (!dbInterface.Login(defaultSchema, username, password, dbCallback)) { // Close after 12 tries. if (authenticationTries >= 12) { Close(); } else { ++authenticationTries; return(Single(ProtocolConstants.UserAuthenticationFailed)); } } else { state = ClientConnectionState.Processing; return(Single(ProtocolConstants.UserAuthenticationPassed)); } } catch (DataException) { } return(null); } if (state == ClientConnectionState.Processing) { // Process the query return(ProcessQuery(command)); } throw new Exception("Illegal state: " + state); }
private static void HandleSslConnect(ConnectToRemoteState state) { var connectStreamWriter = new StreamWriter(state.ClientStream); connectStreamWriter.WriteLine("HTTP/1.0 200 Connection established"); connectStreamWriter.WriteLine("Timestamp: {0}", DateTime.Now); connectStreamWriter.WriteLine("Proxy-agent: GOS Proxy Service"); connectStreamWriter.WriteLine(); connectStreamWriter.Flush(); var sslStream = new SslStream(state.ClientStream, false); try { var certProvider = new CertificateProvider(); bool created; var certificate = certProvider.LoadOrCreateCertificate(state.RemoteHost, out created); sslStream.AuthenticateAsServer(certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true); } catch (Exception ex) { WriteLog(state.Session, 0, "ERR", ex.Message); sslStream.Close(); state.ClientStream.Close(); connectStreamWriter.Close(); return; } var nstate = new ClientConnectionState { Session = state.Session, Client = state.Client, ClientStream = sslStream, ClientStreamBase = (NetworkStream)state.ClientStream, Buffer = new byte[Globals.BufferSize], MessageStream = new MemoryStream(), IsSsl = true, }; try { sslStream.BeginRead(nstate.Buffer, 0, nstate.Buffer.Length, ReadFromClient.Run, nstate); } catch (Exception ex) { WriteLog(state.Session, 0, "ERR", ex.Message); sslStream.Close(); state.ClientStream.Close(); } }
public void ReceiveMessage(PiranhaMessage message) { int messageType = message.GetMessageType(); int messageServiceNodeType = message.GetServiceNodeType(); ClientConnectionState state = this.m_connection.State; if (state != ClientConnectionState.LOGGED) { if (state == ClientConnectionState.DISCONNECTED) { return; } if (messageType != ClientHelloMessage.MESSAGE_TYPE && messageType != LoginMessage.MESSAGE_TYPE && messageType != KeepAliveMessage.MESSAGE_TYPE && messageType != UnlockAccountMessage.MESSAGE_TYPE) { return; } } Logging.Print("MessageManager.receiveMessage: " + message.GetType().Name); if (messageServiceNodeType == 1) { switch (messageType) { case ClientHelloMessage.MESSAGE_TYPE: this.ClientHelloMessageReceived((ClientHelloMessage)message); break; case LoginMessage.MESSAGE_TYPE: this.LoginMessageReceived((LoginMessage)message); break; case KeepAliveMessage.MESSAGE_TYPE: this.KeepAliveMessageReceived((KeepAliveMessage)message); break; case UnlockAccountMessage.MESSAGE_TYPE: this.UnlockAccountMessageReceived((UnlockAccountMessage)message); break; case BindFacebookAccountMessage.MESSAGE_TYPE: this.OnBindFacebookAccountMessageReceived((BindFacebookAccountMessage)message); break; } } else { if (state != ClientConnectionState.LOGGED) { return; } ProxySession session = this.m_connection.Session; if (session == null) { return; } if (this.IsRequestPiranhaMessage(message)) { switch (messageType) { case AskForAvatarProfileMessage.MESSAGE_TYPE: this.SendForwardLogicMessageRequestMessage(message, ServerManager.GetDocumentSocket(9, ((AskForAvatarProfileMessage)message).RemoveAvatarId())); break; case AskForAllianceDataMessage.MESSAGE_TYPE: this.SendForwardLogicMessageRequestMessage(message, ServerManager.GetDocumentSocket(11, ((AskForAllianceDataMessage)message).RemoveAllianceId())); break; } } else if (messageServiceNodeType == 28 || messageServiceNodeType == 29) { this.SendForwardLogicMessageRequestMessage(message, ServerManager.GetNextSocket(messageServiceNodeType)); } else { session.SendPiranhaMessage(message, messageServiceNodeType); } } }
void ReceiveConnectionData(ushort packetTypeIndex, IPEndPoint ipEndPoint, Stream stream) { switch ((PacketType)packetTypeIndex) { case PacketType.ChallengeRequest: if (!UdpNetworkManager.Instance.IsServer && clientConnectionState == ClientConnectionState.RequestingConnection) { ChallengeRequestPacket challengeRequestPacket = new ChallengeRequestPacket(); challengeRequestPacket.Deserialize(stream); challengeResultGeneratedByClient = saltGeneratedByClient ^ challengeRequestPacket.Payload.serverSalt; clientConnectionState = ClientConnectionState.SendingChallengeResponse; } break; case PacketType.ConnectionAccepted: if (!UdpNetworkManager.Instance.IsServer && clientConnectionState == ClientConnectionState.SendingChallengeResponse) { ConnectionAcceptedPacket connectionAcceptedPacket = new ConnectionAcceptedPacket(); connectionAcceptedPacket.Deserialize(stream); UdpNetworkManager.Instance.SetClientID(connectionAcceptedPacket.Payload.clientID); onClientConnectedCallback?.Invoke(connectionAcceptedPacket.Payload.clientsInSession); onClientConnectedCallback = null; clientConnectionState = ClientConnectionState.Connected; } break; case PacketType.ClientJoined: if (!UdpNetworkManager.Instance.IsServer && clientConnectionState == ClientConnectionState.Connected) { ClientJoinedPacket clientJoinedPacket = new ClientJoinedPacket(); clientJoinedPacket.Deserialize(stream); OnOtherClientJoined.Invoke(clientJoinedPacket.Payload.clientID); } break; case PacketType.ConnectionRequest: if (UdpNetworkManager.Instance.IsServer && !udpClientsIDs.ContainsKey(ipEndPoint)) { if (!udpPendingClientsData.ContainsKey(ipEndPoint)) { ConnectionRequestPacket connectionRequestPacket = new ConnectionRequestPacket(); connectionRequestPacket.Deserialize(stream); AddPendingClient(ipEndPoint, connectionRequestPacket.Payload.clientSalt); } UdpPendingClientData udpPendingClientData = udpPendingClientsData[ipEndPoint]; SendChallengeRequest(udpPendingClientData); } break; case PacketType.ChallengeResponse: if (UdpNetworkManager.Instance.IsServer) { if (udpPendingClientsData.ContainsKey(ipEndPoint)) { ChallengeResponsePacket challengeResponsePacket = new ChallengeResponsePacket(); UdpPendingClientData udpPendingClientData = udpPendingClientsData[ipEndPoint]; challengeResponsePacket.Deserialize(stream); long serverResult = udpPendingClientData.clientSalt ^ udpPendingClientData.serverSalt; if (challengeResponsePacket.Payload.result == serverResult) { ClientJoinedPacket clientJoinedPacket = new ClientJoinedPacket(); ClientJoinedData clientJoinedData; clientJoinedData.clientID = ClientID; clientJoinedPacket.Payload = clientJoinedData; PacketsManager.Instance.SendPacket(clientJoinedPacket, null, 0, 0, reliable: true); AddClient(ipEndPoint); RemovePendingClient(ipEndPoint); OnClientAddedByServer?.Invoke(udpClientsIDs[ipEndPoint]); } } if (udpClientsIDs.ContainsKey(ipEndPoint)) { SendConnectionAccepted(udpClientsData[udpClientsIDs[ipEndPoint]]); } } break; } }
public void ToClientState(WebSocketState socketState, ClientConnectionState expectedState) { Assert.AreEqual(expectedState, socketState.ToClientState()); }
public void Start() { var wc = new WebClient(); Console.WriteLine("Create job"); JobId = wc.UploadString(Utilities.CombineURL(_cfg.ManagerUrl, "/createjob"), BuildJobInfoJson()); Console.WriteLine("Created manager job " + JobId); Console.WriteLine("Uploading assemblies..."); foreach (var a in _cfg.Assemblies) { var n = Path.GetFileName(a); wc.UploadData(Utilities.CombineURL(_cfg.ManagerUrl, "/job/" + JobId + "/assemblies?name=" + n), File.ReadAllBytes(a)); } Console.WriteLine("Uploading done."); Console.WriteLine("Starting job " + JobId); wc.DownloadString(Utilities.CombineURL(_cfg.ManagerUrl, "/job/" + JobId + "/start")); State = ClientConnectionState.Started; Console.WriteLine("Job " + JobId + " started."); }
private void SetClientConnectionStateTo(ClientConnectionState state) { clientConnectionState = state; }
/// <summary> /// Processes a single Query from the client. /// </summary> /// <param name="command"></param> /// <returns> /// Returns a byte array and the response is written out as a byte array, or /// <b>null</b> if the connection has been closed. /// </returns> protected byte[] ProcessCommand(byte[] command) { if (state == ClientConnectionState.Closed) { // State 0 means we looking for the header... BinaryReader reader = new BinaryReader(new MemoryStream(command), Encoding.ASCII); /* int magic = ByteBuffer.ReadInt4(Query, 0); // The driver version number int maj_ver = ByteBuffer.ReadInt4(Query, 4); int min_ver = ByteBuffer.ReadInt4(Query, 8); */ reader.ReadInt32(); // magic reader.ReadInt32(); // server major version reader.ReadInt32(); // server minor version string databaseName = reader.ReadString(); if (!ChangeDatabaseInterface(controller.Config, databaseName)) return Single(ProtocolConstants.DatabaseNotFound); Version version = Assembly.GetExecutingAssembly().GetName().Version; byte[] ackCommand = new byte[4 + 1 + 4 + 4 + 1]; // Send back an acknowledgement and the version number of the server ByteBuffer.WriteInteger(ProtocolConstants.Acknowledgement, ackCommand, 0); ackCommand[4] = 1; ByteBuffer.WriteInteger(version.Major, ackCommand, 5); ByteBuffer.WriteInteger(version.Minor, ackCommand, 9); ackCommand[13] = 0; // Set to the next state. state = ClientConnectionState.NotAuthenticated; // Return the acknowledgement return ackCommand; } if (state == ClientConnectionState.NotAuthenticated) { // State 4 means we looking for username and password... MemoryStream input = new MemoryStream(command); BinaryReader reader = new BinaryReader(input, Encoding.ASCII); string defaultSchema = reader.ReadString(); string username = reader.ReadString(); string password = reader.ReadString(); try { if (!dbInterface.Login(defaultSchema, username, password, dbCallback)) { // Close after 12 tries. if (authenticationTries >= 12) { Close(); } else { ++authenticationTries; return Single(ProtocolConstants.UserAuthenticationFailed); } } else { state = ClientConnectionState.Processing; return Single(ProtocolConstants.UserAuthenticationPassed); } } catch (DataException) { } return null; } if (state == ClientConnectionState.Processing) // Process the query return ProcessQuery(command); throw new Exception("Illegal state: " + state); }
public override void ConnectionStateUpdated(TwilioChatClient client, ClientConnectionState state) { Logger.Info($"ChatClient: {client}", $"ConnectionStateChange: {state}"); }
// ---------- Primitive _queries ---------- private byte[] ChangeDatabase(int dispatchId, byte[] command) { // Read the query from the Query. MemoryStream input = new MemoryStream(command, 8, command.Length - 8); BinaryReader reader = new BinaryReader(input, Encoding.Unicode); string databaseName = reader.ReadString(); try { dbInterface.ChangeDatabase(databaseName); state = ClientConnectionState.NotAuthenticated; return SimpleSuccess(dispatchId); } catch (DataException e) { return Exception(dispatchId, e); } }