private void HandleConnection(Connection connection) { ThreadPool.QueueUserWorkItem(delegate { OnConnection?.Invoke(this, connection); }); }
// Runs in the scheduler thread. // Doesn't throw. In case of error both `connection` and `reader` are set to null. // Otherwise both are non-null. void NewConnection(out IConnection <In, Out> connection, out Reader <In> reader) { connection = null; var r = new Reader <In>(); try { connection = _connector.NewConnection(); Condition.Requires(connection).IsNotNull(); connection.OnMessage += (TimestampedMsg <In> msg) => r.Push(msg); connection.Connect(); OnConnection?.Invoke(r, new SimpleWriter <In, Out>(connection)); // If OnConnection() handler swallowed read error exceptions, CheckHealth() will throw. r.CheckHealth(); reader = r; } catch (Exception e) { _log.Warn(e, "Unable to connect. Will retry."); if (connection != null) { try { connection.Dispose(); } catch (Exception ex) { _log.Error(ex, "Ignoring exception from IConnection.Dispose()"); } connection = null; } reader = null; } }
private void FinishConnection() { ConnectedBlocks.ForEach(block => block.IsConnected = false); if (ConnectedBlocks.Count >= 3) { if (OnConnection != null) { OnConnection.Invoke(ConnectedBlocks.Count); } Board.RemoveBlocks(ConnectedBlocks); Board.RefreshBlocks(); } if (ConnectedBlocks.Count >= 4) { FindObjectOfType <GameManager>().RemainingTime++; } if (ConnectedBlocks.Count >= 5) { FindObjectOfType <GameManager>().RemainingTime += 3; } ConnectedBlocks.Clear(); CurrentColor = null; RefreshConnector(); }
[ConditionalShow, SerializeField] private bool useless; //在没有数据的时候让标题正常显示 #endif private void Awake() { NetworkSystem.OnUDPReceive += val => OnUDPReceive?.Invoke(val.message); NetworkSystem.OnReceive += val => OnReceive?.Invoke(val); NetworkSystem.OnConnection += () => OnConnection?.Invoke(); NetworkSystem.OnDisconnection += () => OnDisconnection?.Invoke(); }
protected override void FireConnection(Tcp.Connection connection, RequestHead req, string subprotocol, byte[] trail) { Connection newConnection = new Connection(connection, req, new Definition.Connection.ServerMode()); newConnection.SetSubprotocol(subprotocol); OnConnection?.Invoke(newConnection); newConnection.Initiate(trail); }
public IModel Connect(CancellationToken cancellationToken, OnConnection onConnection) { this.cancellationToken = cancellationToken; this.currentConnection = this.GetConnection(); this.currentChannel = this.currentConnection.CreateModel(); onConnection?.Invoke(this.currentChannel, this.connectionOptions); this.isConsumingAlive = true; return(this.currentChannel); }
private void ProcessClient(TcpClient client) { ClientConnection clientConnection = new ClientConnection(client, SERVER_IP, PORT_NO); Console.WriteLine(String.Format("New connection: {0}", client.Client.RemoteEndPoint)); ConnectionArgs args = new ConnectionArgs(clientConnection); OnConnection?.Invoke(this, args); ListenToClient(clientConnection); }
private void SetDisconnected(string message = "Disconnected.") { _connectionStatus = message; CloudFileWatcher.Access.SetAuthorization(null); UserID = ""; _settings.Token = null; OnConnection?.Invoke(this, new OnConnectionEvent { IsSuccess = false }); }
/// <summary> /// Sets a token for the current session. /// </summary> /// <param name="token"></param> private void SetConnected(Token token) { _connectionStatus = "Connected."; CloudFileWatcher.Access.SetAuthorization(token); UserID = token.user_id; _settings.Token = token; OnConnection?.Invoke(this, new OnConnectionEvent { IsSuccess = true }); }
private async Task Accept() { while (_running) { var tcpClient = await _listener.AcceptTcpClientAsync().ConfigureAwait(false); var newXFireClient = new XFireClient(tcpClient, _clientManager, _logger, OnReceive, OnDisconnection); OnConnection?.Invoke(newXFireClient); } }
private async void HandleClient() { while (listener.IsListening) { var context = await listener.GetContextAsync(); if (listener.IsListening) { OnConnection?.Invoke(this, context); } } }
private void ClientHandler(TcpClient client) { ConnectionEventArgs connectionEvent = new ConnectionEventArgs(client); if (connectionEvent.Request.URL == null) { connectionEvent.Response.Close(); return; } OnConnection?.Invoke(this, connectionEvent); }
protected SocketManager() { Namespaces = new Dictionary <string, Namespace>(); var defaultNsp = new Namespace("/"); Default = defaultNsp; lock (Namespaces) { Namespaces.Add("/", defaultNsp); } defaultNsp.OnConnection += socket => { OnConnection?.Invoke((T)socket); }; }
private void SetConnectionState(ConnectionState newState) { var oldState = _connectionState; _connectionState = newState; if (oldState == newState) { return; } Connected = newState == ConnectionState.Connected; OnConnection?.Invoke(_connectionState); }
public ServerConnection(CreateConnection creator) { _thread = new Thread(() => { while (true) { IConnection connection = creator(); OnConnection?.Invoke(this, new ConnectionEventArgs { Socket = connection }); } }); _thread.Start(); }
private async Task Accept() { while (_running) { Context session = new Context(await _listener.AcceptTcpClientAsync().ConfigureAwait(false)); Debug.WriteLine("Client connected {0} and assigned session id {1}", session.TcpClient.Client.RemoteEndPoint, session.SessionId); OnConnection?.Invoke(session); #pragma warning disable 4014 // Fire and forget. Can't be bothered to fix right now. This whole class needs to be rewritten and decoupled Receive(session); #pragma warning restore 4014 } }
public void AddSocket(ISocket socket) { socket.OnDisconnect += (status, reason) => { lock (Sockets) { Sockets?.Remove(socket); } }; lock (Sockets) { Sockets.Add(socket); } OnConnection?.Invoke(socket); }
//Pause connections. Used by aTello when app paused. public void ConnectionSetPause(bool pause) { //NOTE only pause if connected and only un-pause (connect) when paused. if (pause && _connectionState == ConnectionState.Connected) { SetConnectionState(ConnectionState.Paused); } else if (pause == false && _connectionState == ConnectionState.Paused) { //NOTE:send un-pause and not connection event OnConnection?.Invoke(ConnectionState.UnPausing); _connectionState = ConnectionState.Connected; } }
private void ConnectToServer(IPEndPoint endpoint) { try { client = new System.Net.Sockets.TcpClient(); client.Connect(endpoint); } catch (Exception e) { Debug.Log(e.Message); } OnConnection?.Invoke(); ReadServerMessage(); }
internal void InitGamePadHandlers() { _gamePadHandlers = new GamePadHandler[MaxGamePads]; for (int i = 0; i < MaxGamePads; i++) { var handle = _gamePadHandlers[i] = new GamePadHandler(i); // Redirect Events. handle.OnConnection += () => OnConnection?.Invoke(handle); handle.OnDisconnect += () => OnDisconnected?.Invoke(handle); handle.OnButtonDown += (button, value) => OnButtonDown?.Invoke(handle, button, value); handle.OnButtonUp += (button, value) => OnButtonUp?.Invoke(handle, button, value); handle.OnButtonPressed += (button, value) => OnButtonPressed?.Invoke(handle, button, value); handle.OnButtonClicked += (button, value) => OnButtonClicked?.Invoke(handle, button, value); handle.OnButtonReleased += (button, value) => OnButtonReleased?.Invoke(handle, button, value); } }
/// <summary> /// Handle a HTTP Upgrade request. /// </summary> /// <param name="req"></param> /// <param name="conn"></param> public void HandleUpgrade(HttpServerRequest req, TcpSocket socket, ArraySegment <byte> head) { if (!socket.Readable || !socket.Writable) { socket.Destroy(); return; } if (OnConnection == null) { AbortConnection(socket, 400); return; } var upgrade = req.Headers["upgrade"]; var version = req.Headers["sec-websocket-version"]; if ((version != "13" && version != "8") || !string.Equals(upgrade, "websocket", StringComparison.InvariantCultureIgnoreCase)) { socket.Write(Encoding.ASCII.GetBytes( "HTTP/1.1 400 Bad Request\r\n" + "Connection: close\r\n" + "Sec-WebSocket-Version: 13, 8\r\n")); socket.Close(); return; } string acceptKey; using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider()) { var key = req.Headers["sec-websocket-key"]; acceptKey = Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(key + GUID))); } socket.Write(Encoding.UTF8.GetBytes( "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Accept: " + acceptKey + "\r\n\r\n")); socket.Flush(); OnConnection.Invoke(new WebSocket(socket, req, head)); }
public bool TryConnect() { _logger.LogInformation("RabbitMQ Client is trying to connect"); if (IsConnected) { return(true); } lock (sync_root) { var policy = RetryPolicy.Handle <SocketException>() .Or <BrokerUnreachableException>() .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => { _logger.LogWarning($"RabbitMQ Client could not connect after {time.TotalSeconds:n1}s ({ex.Message})"); } ); policy.Execute(() => { _connection = _connectionFactory .CreateConnection(); }); if (IsConnected) { _connection.ConnectionShutdown += OnConnectionShutdown; _connection.CallbackException += OnCallbackException; _connection.ConnectionBlocked += OnConnectionBlocked; OnConnection?.Invoke(this, _connection); return(true); } else { _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened"); LoopTryConnect(); return(false); } } }
private void FinishConnection() { _connectedBlocks .ForEach(block => block.isConnected = false); if (_connectedBlocks.Count >= 3) { if (OnConnection != null) { OnConnection.Invoke(_connectedBlocks.Count); } _board.RemoveConnectedBlocks(_connectedBlocks); _board.RefreshBlocks(); } _connectedBlocks.Clear(); _currentColor = null; RefreshConnection(); }
/// <summary> /// funkcja wyświetlana w momencie, gdy użytkownik przestawał dotykać ekran /// </summary> private void FinishConnection() { ConnectedBlocks .ForEach(block => block.IsConnected = false); if (ConnectedBlocks.Count >= 3) // sprawdzenie czy gracz połączył przynajmniej 3 bloki { if (OnConnection != null) { OnConnection.Invoke(ConnectedBlocks.Count); } Board.RemoveBlocks(ConnectedBlocks); // usuwanie poszczególnych bloków Board.RefreshBlocks(); // przesunięcie poszczególnych elementów na planszy } ConnectedBlocks.Clear(); CurrentColor = null; RefreshConnector(); }
private void FinishConnection() { ConnectedBlocks .ForEach(block => block.IsConnected = false); if (ConnectedBlocks.Count >= 3) { if (OnConnection != null) { OnConnection.Invoke(ConnectedBlocks.Count); } Board.RemoveBlocks(ConnectedBlocks); Board.RefreshBlocks(); } ConnectedBlocks.Clear(); CurrentColor = null; RefreshConnection(); }
public async Task ConnectionStartAsync(Uri uri) { await Task.Run(() => { try { _info = new IBusService.ConnectionInfo(uri, MqttConfiguration.TopicMatcher(uri)); _error = null; _client = new MqttClient(uri.Host, uri.Port, false, null, null, MqttSslProtocols.None) { ProtocolVersion = MqttProtocolVersion.Version_3_1 }; var code = default(byte); if (string.IsNullOrEmpty(uri.UserInfo)) { code = _client.Connect(Guid.NewGuid().ToString()); } else { var bUri = new UriBuilder(uri); code = _client.Connect(Guid.NewGuid().ToString(), bUri.UserName, bUri.Password); } _client.Subscribe(new[] { _info.Topic }, new[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); _client.MqttMsgPublishReceived += DefaultClient_MqttMsgPublishReceived; OnConnection?.Invoke(code); } catch (Exception e) { _error = e; } finally { OnStatusChange?.Invoke(GetConnectionStatus(), _info); } }); }
public async Task Start() { await using var ctx = new NovaContext(); await ctx.EnsureUpdatedAsync(); _server.Start(); RegisterAssembly(typeof(Server).Assembly); RegisterAssembly(Assembly.GetEntryAssembly()); _server.NewConnection += point => { var connection = new Connection(point, _server); Connections.Add(connection); OnConnection?.Invoke(connection); }; _server.Disconnection += point => { var connection = Connections.FirstOrDefault(c => c.EndPoint.Equals(point)); if (connection == default) { return; } Connections.Remove(connection); OnDisconnect?.Invoke(connection); }; _server.PacketReceived += (point, bytes) => { var connection = Connections.FirstOrDefault(c => c.EndPoint.Equals(point)); if (connection == default) { Logger.Warning($"{point} is not connected but we still got data from them!"); return; } using var stream = new MemoryStream(bytes); using var reader = new BitReader(stream); var id = (MessageIdentifiers)reader.Read <byte>(); if (id != MessageIdentifiers.UserPacketEnum) { Logger.Error($"Invalid packet: {id}"); return; } HandlePacket(reader, connection); reader.BaseStream.Position = 0; OnPacket?.Invoke(connection, reader); }; var request = ctx.WorldServerRequests.FirstOrDefault(w => w.SpecificationId == Id); if (request != default) { Logger.Information($"Request found for {Id}"); request.State = WorldServerRequestState.Complete; await ctx.SaveChangesAsync(); } await ctx.DisposeAsync(); while (true) { var command = Console.ReadLine(); } }
/// <summary> /// As a server, we will listen on the main socket /// and spawn of other sockets for incomming connetions. /// /// Those connections will be maintined untill the die /// </summary> private void Listen() { IPAddress [] addresses = Dns.GetHostAddresses(Dns.GetHostName()); // Create a TCP/IP socket. foreach (IPAddress curAddr in addresses) { try { IPEndPoint ipe = new IPEndPoint(curAddr, Port); connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); connection.Bind(ipe); connection.Blocking = false; connection.Listen(10); IsListining = true; break; } catch (SocketException) { //something mesed up during our connection attempt. //Wont crash out of the loop since we might have more IPs to try continue; } } if (!IsListining) { OnConnection?.Invoke("listen", ConnectionStatus.Failure); } else { OnConnection?.Invoke("listen", ConnectionStatus.Succes); Listner = new Thread(() => { while (true) { if (!KillConnection) { try { Socket tempListener = connection.Accept(); OnConnection?.Invoke(Address + ":" + Port, ConnectionStatus.Succes); new Thread((soc) => { Socket tempSocket = soc as Socket; while (true) { byte[] buffer = new byte[MsgSize]; if (KillConnection) { tempSocket.Shutdown(SocketShutdown.Both); } int size = 0; try { size = tempSocket.Receive(buffer); String temp = Util.BtoS(buffer); OnMsg?.Invoke(tempSocket, temp); } catch (SocketException e) { if (e.ErrorCode == (int)SocketError.ConnectionAborted || e.ErrorCode != (int)SocketError.WouldBlock) { KillConnection = true; size = 0; } } catch (ObjectDisposedException) { break; } if (size == 0 && KillConnection) { OnBadThing?.Invoke(); tempSocket.Close(); tempSocket.Dispose(); break; } Thread.Sleep(100); } OnConnection?.Invoke(Address + ":" + Port, ConnectionStatus.Failure); }).Start(tempListener); } catch (SocketException e) { //If the accept call has nothing to accept, this will do nothing //All other errors are re-thrown. if (e.ErrorCode != (int)SocketError.WouldBlock) { throw e; } } } else { try { connection.Shutdown(SocketShutdown.Both); } catch (SocketException) { //The socket was not connected/listening. } connection.Close(); connection.Dispose(); break; } Thread.Sleep(100); } }); Listner.Start(); } }
internal void FireConnection(TcpSocket socket) => OnConnection?.Invoke(socket);
/// <summary> /// Tries to connect to a server, and then start a listing loop. /// </summary> private void Connect() { if (String.IsNullOrEmpty(Address)) { return; } IPAddress [] addresses; if (Address == "localhost") { addresses = Dns.GetHostAddresses(Dns.GetHostName()); } else { addresses = Dns.GetHostAddresses(Address); } // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception that occurs when the host IP Address is not compatible with the address family // (typical in the IPv6 case). foreach (IPAddress curAddr in addresses) { try { IPEndPoint ipe = new IPEndPoint(curAddr, Port); connection = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); connection.Connect(ipe); //If we connect, start a simple listining loop. if (connection.Connected) { OnConnection?.Invoke(Address + ":" + Port, ConnectionStatus.Succes); Listner = new Thread(() => { while (true) { byte[] buffer = new byte[MsgSize]; int size = 0; try { size = connection.Receive(buffer); } catch (SocketException) { KillConnection = true; size = 0; } if (size == 0 && KillConnection) { OnBadThing?.Invoke(); connection.Close(); connection.Dispose(); break; } //connection.Send(buffer); String temp = Util.BtoS(buffer); OnMsg?.Invoke(connection, temp); Thread.Sleep(100); } }); Listner.Start(); return; } else { continue; } } catch (SocketException) { //something mesed up during our connection attempt. //Wont crash out of the loop since we might have more IPs to try continue; } } OnConnection?.Invoke(Address + ":" + Port, ConnectionStatus.Failure); connection = null; }