/// <summary> /// Update the list of current connections. /// </summary> /// <param name="connections">The list of active connections.</param> /// <param name="callback">A callback to invoke for each new connection in <paramref name="connections"/>. /// May be null</param> /// <remarks> /// The internal connections list is updated to match <paramref name="connections"/>. /// /// This method is called by the <see cref="ConnectionMonitor"/> and should not be /// called directly. /// </remarks> public void UpdateConnections(IList <IConnection> connections, NewConnectionCallback callback = null) { _lock.Lock(); try { List <IConnection> newConnections = new List <IConnection>(); if (connections.Count > 0) { // Collate new connections. newConnections = new List <IConnection>(); for (int i = 0; i < connections.Count; ++i) { bool existing = false; for (int j = 0; j < _connections.Count; ++j) { if (connections[i] == _connections[j]) { existing = true; break; } } if (!existing) { newConnections.Add(connections[i]); } } } // Update internal connections list. _connections.Clear(); for (int i = 0; i < connections.Count; ++i) { _connections.Add((TcpConnection)connections[i]); } // Add cache only to new connections. for (int i = 0; i < newConnections.Count; ++i) { newConnections[i].SendServerInfo(ServerInfo); if (callback != null) { callback(this, newConnections[i]); } } } finally { _lock.Unlock(); } }
public void ListenForConnections(string IP, int port, NewConnectionCallback new_connection_callback, int max_connections = 1) { _socket.Bind(new IPEndPoint(IPAddress.Parse(IP), port)); _socket.Listen(max_connections); Task.Run(() => { while (true) { Socket new_connection = _socket.Accept(); new_connection_callback(new NetworkSocket(new_connection)); } }); }
/// <summary> /// Осуществляет подключение к командному обработчику и выполняет действия /// необходимые при первом подключении клиента к серверу. /// </summary> protected async Task ConnectToCommandHandlerAsync(IPEndPoint endPoint) { mainConnection = new Connection(endPoint); ConnectionCallback callback = new NewConnectionCallback(mainConnection); await mainConnection.OpenAsync(callback).ConfigureAwait(false); Guid[] ids = (Guid[])callback.Result; mainConnection.InitializationOnClient(ids[0], ids[1]); ID = ids[0]; clientListener = new ClientListener(mainConnection, cSource.Token); }
/// <summary> /// Commit new and expired connections to the list and update the <see cref="IServer"/>. /// </summary> /// <param name="callback">The callback to invoke for each new connection. May be null.</param> /// <remarks> /// Must be called from the main thread, regardless of mode, to ensure the /// server reflects the current connection list. /// </remarks> public void CommitConnections(NewConnectionCallback callback = null) { bool locked = false; _lock.Lock(); locked = true; try { _server.UpdateConnections(_connections, callback); _lock.Unlock(); locked = false; } finally { if (locked) { _lock.Unlock(); } } }