// 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 HandleConnection(Connection connection) { ThreadPool.QueueUserWorkItem(delegate { OnConnection?.Invoke(this, connection); }); }
private void Listen() { int i = 0; try { for (i = 0; i <= MaxConnection; ++i) { clientSocket.Add(Accept()); OnConnection.BeginInvoke(clientSocket[i].RemoteEndPoint.ToString(), null, null); clientSocket[i].Blocking = true; clientSocket[i].SendBufferSize = _SendBufferSize; clientSocket[i].ReceiveBufferSize = _ReceiveBufferSize; Thread t = new Thread(Received); t.IsBackground = true; t.Name = i.ToString(); t.Priority = ThreadPriority.Lowest; t.Start(); } } catch { Error_Message = "服务器已停止"; OnError.BeginInvoke(Error_Message, null, null); CloseSocket(i); } }
private void AcceptClient_ClientDisconnected(OnConnection clientConnection) { BaseProtocol ci = (BaseProtocol)clientConnection; ci.ClientClosed -= AcceptClient_ClientDisconnected; Clients.Remove(ci); }
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(); }
private static void AcceptClient_ClientDisconnected(OnConnection clientConnection) { FTPModule ci = (FTPModule)clientConnection; ci.ClientClosed -= AcceptClient_ClientDisconnected; Program.Clients.Remove(ci); }
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 SetDisconnected(string message = "Disconnected.") { _connectionStatus = message; CloudFileWatcher.Access.SetAuthorization(null); UserID = ""; _settings.Token = null; OnConnection?.Invoke(this, new OnConnectionEvent { IsSuccess = false }); }
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); }
/// <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(); }
public void AddSocket(ISocket socket) { socket.OnDisconnect += (status, reason) => { lock (Sockets) { Sockets?.Remove(socket); } }; lock (Sockets) { Sockets.Add(socket); } OnConnection?.Invoke(socket); }
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 } }
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(); }
//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; } }
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(); }
/// <summary> /// 连接 /// </summary> /// <returns>成功返回TRUE</returns> public bool ConnectionServer() { try { IPEndPoint _ip = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port); this.Connect(_ip); this.SendBufferSize = _SendBufferSize; this.ReceiveBufferSize = _ReceiveBufferSize; OnConnection.BeginInvoke(null, null); Thread t = new Thread(Receive);//数据返回监视 t.IsBackground = true; t.Priority = ThreadPriority.Lowest; t.Start(); return(true); } catch (Exception e) { Error_Message = e.Message; OnError(e.Message); return(false); } }
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); } }); }