void OnGameConnClose(int code, string reason) { context.Post(() => { state = PlayState.DISCONNECT; OnDisconnected?.Invoke(); }); }
internal override void InvokeEvent(ServerType type, IConnection conn, IMessage msg) { switch (type) { case ServerType.Started: OnStarted?.Invoke(conn, msg); break; case ServerType.Accepted: OnAccepted?.Invoke(conn, msg); break; case ServerType.Sended: OnSended?.Invoke(conn, msg); break; case ServerType.Received: OnRecieved?.Invoke(conn, msg); break; case ServerType.Disconnected: OnDisconnected?.Invoke(conn, msg); break; case ServerType.Stopped: OnStopped?.Invoke(conn, msg); break; } }
protected override void OnReceiveInternalData(InternalMessages type, CSteamID clientSteamID) { switch (type) { case InternalMessages.CONNECT: if (steamToMirrorIds.Count >= maxConnections) { SendInternal(clientSteamID, InternalMessages.DISCONNECT); return; } SendInternal(clientSteamID, InternalMessages.ACCEPT_CONNECT); int connectionId = nextConnectionID++; steamToMirrorIds.Add(clientSteamID, connectionId); OnConnected.Invoke(connectionId); Debug.Log($"Client with SteamID {clientSteamID} connected. Assigning connection id {connectionId}"); break; case InternalMessages.DISCONNECT: if (steamToMirrorIds.TryGetValue(clientSteamID, out int connId)) { OnDisconnected.Invoke(connId); CloseP2PSessionWithUser(clientSteamID); steamToMirrorIds.Remove(clientSteamID); Debug.Log($"Client with SteamID {clientSteamID} disconnected."); } break; default: Debug.Log("Received unknown message type"); break; } }
public async Task Disconnect() { try { if (Logger == null) { throw new HoloNETException("ERROR: No Logger Has Been Specified! Please set a Logger with the Logger Property."); } if (WebSocket.State != WebSocketState.Closed && WebSocket.State != WebSocketState.Aborted && WebSocket.State != WebSocketState.CloseSent && WebSocket.State != WebSocketState.CloseReceived) { Logger.Log(string.Concat("Disconnecting from ", EndPoint, "..."), LogType.Info); await WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client manually disconnected.", CancellationToken.None); if (WebSocket.State == WebSocketState.Closed) { // Close any conductors down if necessary. ShutDownConductors(); Logger.Log(string.Concat("Disconnected from ", EndPoint), LogType.Info); OnDisconnected?.Invoke(this, new DisconnectedEventArgs { EndPoint = EndPoint, Reason = "Disconnected Method Called." }); } } } catch (Exception e) { HandleError(string.Concat("Error occured disconnecting from ", EndPoint), e); } }
private void _cnn_OnDisconnected(string ID, Exception ex) { OnDisconnected?.Invoke(this.IPPort); IsConnected = false; ThreadHelper.Sleep(1000); Connect(); }
//void Sent(IAsyncResult ar) { // var stream = (ar.AsyncState as NetworkStream); // stream.EndWrite(ar); //} void Recieve(TcpClient client) { var stream = client.GetStream(); while (_connected) { if (stream.CanRead) { try { var recievedBytes = _packetIO.Recieve(); OnRecieved?.Invoke(recievedBytes); //int incomingBytes = stream.ReadByte(); //byte[] buffer = new byte[incomingBytes]; //stream.BeginRead( // buffer, 0, incomingBytes, // new AsyncCallback(Recieved), // new ReadResult { // Buffer = buffer, // Stream = stream // }); //_wait.WaitOne(); } catch (IOException) { _connected = false; } } } OnDisconnected?.Invoke(); }
public bool Disconnect(string reasone = "Disconnected") { if (!this.Status) { Console.WriteLine("Disconnecting has been failed: You dont have connection!"); return(false); } try { if (this.IsConnected) { this.BaseSocket?.Client.SendTo(new byte[] { 254, 254, 254, 254 }, this.ConnectedEndPoint); } var connection = this.Connection; this.Status = false; this.BaseSocket?.Close(); this.BaseSocket = null; this.m_startConnectionTime = 0; this.m_countFailedTick = 1; this.ConnectedEndPoint = null; this.m_listconnections.Clear(); OnDisconnected?.Invoke(connection, reasone); return(true); } catch (Exception exception) { Console.WriteLine($"Disconnecting has been failed: " + exception.Message); } return(false); }
private void InternalDisconnect() { Connected = false; OnDisconnected.Invoke(); Debug.Log("Disconnected."); SteamNetworkingSockets.CloseConnection(HostConnection, 0, "Disconnected", false); }
protected void AxMsRdpClient_OnDisconnected(object sender, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEvent e) { var reason = DisconnectReason.ConnectionTerminated; // https://social.technet.microsoft.com/wiki/contents/articles/37870.rds-remote-desktop-client-disconnect-codes-and-reasons.aspx // https://msdn.microsoft.com/en-us/library/aa382170%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 switch (e.discReason) { case Reason_ClientDisconnect: case Reason_ServerDisconnect: reason = DisconnectReason.ConnectionEnded; break; case Reason_DisconnectedByUser: reason = DisconnectReason.KickedOut; break; case Reason_ServerNotFound: reason = DisconnectReason.ServerNotFound; break; case Reason_TimedOut: reason = DisconnectReason.ConnectionTimedOut; break; } OnDisconnected?.Invoke(this, reason); }
public bool Disconnect() { if (Connected) { try { //Disconnect the TcpClient client.Close(); } catch (Exception ex) { Logger.Error("Failed to disconnect : " + ex.Message, DebugLevel); return(false); } } //Invoke the event if (OnDisconnected != null) { OnDisconnected.Invoke(); } return(true); }
protected override void Cleanup() { if (ether != null) { if (ether.Connected) { OnDisconnecting?.Invoke(this); //Update all writable registers one last time. for (int id = 0; id < MaxNumDevices; id++) { if (registers[id] != null) { byte[] update = registers[id].SendUpdate; if ((update != null) && (update.Length > 0)) { ether?.Send(new UdpPacket((byte)id, update)); } } } } ether.Disconnect(); ether.OnPacketReceived -= Ether_OnPacketReceived; } ThreadPool.QueueUserWorkItem(new WaitCallback((object callback) => { OnDisconnected?.Invoke(); })); }
private async void InteractWithClient(Socket client, Func <Socket, CancellationToken, Task> clientInteraction, CancellationToken token) { var socketInfo = new SocketEndpoints(); try { using (client) { socketInfo = new SocketEndpoints(client); OnConnected?.Invoke(client); await clientInteraction(client, token).ConfigureAwait(false); } } catch (OperationCanceledException ex) { OnCancelled?.Invoke(socketInfo, ex); } catch (Exception ex) { OnException?.Invoke(socketInfo, ex); } finally { OnDisconnected?.Invoke(socketInfo); } }
private void _client_OnDisconnected(object sender, CloseEventArgs e) { OnDisconnected?.Invoke(this, new OnDisconnectedArgs { Username = TwitchUsername }); JoinedChannels.Clear(); }
/// <summary> /// Listens to incoming messages, and starts async receivers (blocking call) /// </summary> private void ReceiveAsync() { using (var receiveDone = new ManualResetEvent(false)) { while (IsConnected) { _ = receiveDone.Reset(); var state = new StateObject { length = 2, bytes = new byte[2], signal = receiveDone }; try { _ = _socket.BeginReceive(state.bytes, 0, state.length, 0, MessageLengthReceivedCallback, state); } catch (Exception ex) { System.Console.WriteLine("Exception caught: {0}", ex.Message); } _ = receiveDone.WaitOne(); } } OnDisconnected.Invoke(this); }
private void SetEventHandlers(Options opts) { opts.AsyncErrorEventHandler += (sender, args) => OnAsyncError?.Invoke(this, ErrorEventArguments.FromNatsEntity(args)); opts.ServerDiscoveredEventHandler += (sender, args) => OnServerDiscovered?.Invoke(this, ConnectionEventArguments.FromNatsEntity(args)); opts.ClosedEventHandler += (sender, args) => OnClosed?.Invoke(this, ConnectionEventArguments.FromNatsEntity(args)); opts.DisconnectedEventHandler += (sender, args) => OnDisconnected?.Invoke(this, ConnectionEventArguments.FromNatsEntity(args)); }
private void OnObsDisconnected(object sender, EventArgs e) { ConnectionFailures++; LastConnectionFailure = DateTimeOffset.UtcNow; OnDisconnected?.Invoke(this, e); ConnectOBS(); }
protected override void OnReceiveInternalData(InternalMessages type, ProductUserId clientUserId) { switch (type) { case InternalMessages.CONNECT: if (epicToMirrorIds.Count >= maxConnections) { SendInternal(clientUserId, InternalMessages.DISCONNECT); return; } SendInternal(clientUserId, InternalMessages.ACCEPT_CONNECT); int connectionId = nextConnectionID++; epicToMirrorIds.Add(clientUserId, connectionId); OnConnected.Invoke(connectionId); Debug.Log($"Client with Product User ID {clientUserId} connected. Assigning connection id {connectionId}"); break; case InternalMessages.DISCONNECT: if (epicToMirrorIds.TryGetValue(clientUserId, out int connId)) { OnDisconnected.Invoke(connId); CloseP2PSessionWithUser(clientUserId); epicToMirrorIds.Remove(clientUserId); Debug.Log($"Client with Product User ID {clientUserId} disconnected."); } else { OnReceivedError.Invoke(-1, new Exception("ERROR Unknown Product User ID")); } break; default: Debug.Log("Received unknown message type"); break; } }
/// <summary> /// Send <see cref="AsyncCallback"/> method. /// </summary> protected virtual void SendCallback(IAsyncResult ar) { try { lock (MLock) { MSendReadyFlag = false; while (!MSendReadyFlag && (MSendQueue.Count > 0)) { byte[] buffer = MSendQueue.Dequeue(); MSocket.BeginSend(buffer, 0, buffer.Length, 0, MSendCallback, null); } MSendReadyFlag = true; } } catch (Exception e) { Logger.Exception(e); CloseConnection(); OnDisconnected?.Invoke(-1, this, ConnectionId); } }
public async Task DisconnectClientAsync(bool dispose = false) { Config.DisconnectClient(); if (Config.ClientConnection.Connected) { Config.ClientConnection.Disconnect(true); } while (Config.ClientConnection.Connected) { Logger.Log("Waiting for client to disconnect..."); await Task.Delay(5).ConfigureAwait(false); } Logger.Log($"Disconnected client => {Config.IpAddress}"); OnDisconnected?.Invoke(this, new OnDisconnectedEventArgs(Config.IpAddress, Config.Uid, 5000)); if (dispose) { Config.ClientConnection?.Close(); Config.ClientConnection?.Dispose(); JobManager.AddJob(() => { TCPServerCore.RemoveClient(this); }, TimeSpan.FromSeconds(5)); } }
private void OnConnDisconnected(int connId, object sender, MqttClientDisconnectedEventArgs args) { if (_connection != null && _connection.Id != connId) { FizzLogger.W("Received disconnected event for old connection."); } FizzLogger.D("MQTT - OnDisconnected: " + args.ClientWasConnected.ToString()); if (OnDisconnected != null) { if (args.Exception == null) { OnDisconnected.Invoke(null); } else { if (args.Exception.GetType() == typeof(MQTTnet.Adapter.MqttConnectingFailedException)) { OnDisconnected.Invoke(ERROR_AUTH_FAILED); if (_sessionRepo != null) { _sessionRepo.FetchToken(null); } } else { OnDisconnected.Invoke(ERROR_CONNECTION_FAILED); } } } }
void onVoiceCommand(VoicePaketCommand args, NetPeer peer) { try { VoicePlugin.Log("VoiceCommand {0} => {1}", args.Command, args.Data); if (args.Command == "DISCONNECT") { _needConnection = false; var Connection = Client.GetFirstPeer(); Connection?.Disconnect(); Connection = null; var con = VoicePlugin.GetConnection(_connectionInfo.ServerGUID); if (con != null) { con.DisconnectVoiceServer(); } OnDisconnected?.Invoke(this, this); return; } if (args.Command == "SETNAME") { var con = VoicePlugin.GetConnection(_connectionInfo.ServerGUID); if (con != null) { con.ConnectVoiceServer(args.Data); } } } catch (Exception ex) { VoicePlugin.Log(ex.ToString()); } }
void Listener_OnDisconnected(FizzException obj) { if (OnDisconnected != null) { OnDisconnected.Invoke(obj); } }
public async Task SendAsync(byte[] data, CancellationToken token = default(CancellationToken)) { try { await _stream.WriteAsync(data, 0, data.Length, token).ConfigureAwait(false); await _stream.FlushAsync(token).ConfigureAwait(false); } catch (IOException ex) { if (ex.InnerException != null && ex.InnerException is ObjectDisposedException) // for SSL streams { } else { OnDisconnected?.Invoke(this, EventArgs.Empty); } } catch (Exception e) { Thread.Sleep(500); Console.WriteLine(e.Message); // await SendAsync(data, token); } }
async void ReadAsync() { while (TcpClient.Connected) { try { int read = await TcpClient.GetStream().ReadAsync(buffer, bufferPos, buffer.Length - bufferPos); if (read <= 0) { Thread.Sleep(250); continue; } bufferPos += read; if (bufferPos < 3) { Thread.Sleep(250); continue; } byte[] header = new byte[4]; Array.Copy(buffer, 0, header, 0, 4); if (BitConverter.IsLittleEndian) { Array.Reverse(header); } int len = BitConverter.ToInt32(header, 0); if (len > 0 && bufferPos >= len) { byte[] data = new byte[len]; Array.Copy(buffer, 4, data, 0, len); var packet = new PacketReader <TOpcode>(data); if (OnDataReceived == null) { logger.Warn($"No handler found for opcode: {packet.Opcode}"); } OnDataReceived?.Invoke(this, new TcpPacketEventArgs <TOpcode> { TcpClient = this, Packet = packet }); int extra = bufferPos - (len + 4); Array.Copy(buffer, len + 4, buffer, 0, extra); bufferPos = extra; } } catch (IOException) { if (TcpClient.Connected) { Thread.Sleep(125); } } } logger.Debug($"Client {Id} disconnected"); OnDisconnected?.Invoke(this, new TcpSocketEventArgs <TOpcode>(this)); }
private void Update() { if (fireOnConnected) { OnConnected?.Invoke(); fireOnConnected = false; } if (fireOnDisconnected) { OnDisconnected?.Invoke(); fireOnDisconnected = false; } if (Status == ConnectionStatus.Connected) { while (_queuedCommands.Dequeue(out var packet)) { OnMessageReceived?.Invoke(packet.channel, packet.command, packet.payload); } if (Math.Abs(LastHeartbeatTime - DateTimeOffset.Now.ToUnixTimeMilliseconds()) > HEARTBEAT_TIMEOUT_THRESHOLD_MS) { Status = ConnectionStatus.Disconnected; Debug.Log("Connection lost, trying to reconnect..."); } } if (Status == ConnectionStatus.Disconnected && !String.IsNullOrEmpty(WebServerAddress.Current)) { Connect(); } }
protected override void OnReceiveInternalData(InternalMessages type, CSteamID clientSteamID) { switch (type) { case InternalMessages.ACCEPT_CONNECT: if (!Connected) { Connected = true; OnConnected.Invoke(); Debug.Log("Connection established."); } break; case InternalMessages.DISCONNECT: if (Connected) { Connected = false; Debug.Log("Disconnected."); OnDisconnected.Invoke(); } break; default: Debug.Log("Received unknown message type"); break; } }
public void Disconnect() { lock (_lock) { try { _state.Size = CmppConstants.HeaderSize; _state.PackageType = typeof(CmppHead); _state.Header = null; lock (_receiveQueue) _receiveQueue.Clear(); if (_socket == null) { return; } _socket.Disconnect(false); _socket.Dispose(); } finally { _socket = null; if (OnDisconnected != null) { OnDisconnected.Invoke(this, null); } } } }
private void OnConnDisconnected(object sender, FizzMqttDisconnectedArgs args) { FizzLogger.D("MQTT - OnDisconnected: " + args.ClientWasConnected.ToString()); if (OnDisconnected != null) { if (args.Exception == null) { OnDisconnected.Invoke(null); } else { if (args.Exception.GetType() == typeof(FizzMqttAuthException)) { OnDisconnected.Invoke(ERROR_AUTH_FAILED); if (_sessionRepo != null) { _sessionRepo.FetchToken(null); } } else { OnDisconnected.Invoke(ERROR_CONNECTION_FAILED); } } } if (_closeCallback != null) { FizzUtils.DoCallback(_closeCallback); } }
public void HandleMessages() { NetIncomingMessage message; while ((message = m_Server.ReadMessage()) != null) { switch (message.MessageType) { case NetIncomingMessageType.ConnectionApproval: try { var packet = Packet.Read(message.Data); ApproveConnection(message.SenderConnection); OnConnectionApproved?.Invoke(new LidgrenMessage(message)); } catch (Exception e) { DenyConnection(message.SenderConnection); OnConnectionDenied?.Invoke(new LidgrenMessage(message)); } break; case NetIncomingMessageType.StatusChanged: switch (message.SenderConnection.Status) { case NetConnectionStatus.Connected: OnConnected?.Invoke(new LidgrenMessage(message)); break; case NetConnectionStatus.Disconnected: OnDisconnecting?.Invoke(new LidgrenMessage(message)); //not firing from lidgren OnDisconnected?.Invoke(new LidgrenMessage(message)); break; } break; case NetIncomingMessageType.Data: TriggerCallback(new LidgrenConnection(message.SenderConnection), message.Data); OnReceivedData?.Invoke(new LidgrenMessage(message)); break; case NetIncomingMessageType.DebugMessage: // handle debug messages // (only received when compiled in DEBUG mode) Console.WriteLine("DEBUG: " + message.ReadString()); break; case NetIncomingMessageType.WarningMessage: Console.WriteLine("WARNING: " + message.ReadString()); break; /* .. */ default: Console.WriteLine("unhandled message with type: " + message.MessageType); break; } } }
public void Disconnect() { Listening = false; Client.Close(); _cancel.Cancel(); HandleDisconnected(); OnDisconnected?.Invoke(this); }