// Adds an incoming connection to the queue private void Listen(IAsyncResult Result) { // Check if server is bound if (Listener.Server.IsBound) { try { // Get incoming connection var Connection = Listener.EndAcceptTcpClient(Result); // Lock our connection queue to prevent any race conditions lock (ConnectionQueue) { // Add the incoming connection to our connection queue ConnectionQueue.Enqueue(Connection); // Signal that a connection is ready to be accepted ReadyEvent.Set(); } // Start listening again Listener.BeginAcceptTcpClient(Listen, null); } catch { } } }
public virtual void ReleaseConnection(Connection connection) { String lHost = connection.OriginalEndpoint.ToString(); if (!connection.Connected) { connection.Dispose(); return; } lock (fSyncRoot) { ConnectionQueue lQueue; if (this.fCache.ContainsKey(lHost)) { lQueue = (ConnectionQueue)this.fCache[lHost]; } else { lQueue = new ConnectionQueue(this.fMaxQueuePerHost == 0 ? 8 : fMaxQueuePerHost); this.fCache.Add(lHost, lQueue); } if (lQueue.Count < this.fMaxQueuePerHost || this.fMaxQueuePerHost < 1) { connection.LastUsed = DateTime.UtcNow; lQueue.Enqueue(connection); } else { connection.Dispose(); } } }
private void CleanupCallback(Object state) { DateTime ExpireTime = DateTime.UtcNow.AddSeconds(-this.Timeout); lock (fSyncRoot) { foreach (string key in this.fCache.Keys) { ConnectionQueue lQueue = fCache[key]; Boolean lModified = false; for (Int32 i = lQueue.UnderlyingArray.Length - 1; i >= 0; i--) { if (lQueue.UnderlyingArray[i] == null || lQueue.UnderlyingArray[i].LastUsed >= ExpireTime) { continue; } lModified = true; lQueue.UnderlyingArray[i].Dispose(); lQueue.UnderlyingArray[i] = null; } if (lModified) { lQueue.RemoveNulls(); } } } }
/// <summary> /// Removes a specific connection to the connection queue. /// </summary> public void RemoveFromQueue(ConnectionCore connection) { if (ConnectionQueue.Contains(connection)) { ConnectionQueue.Remove(connection); ServerLogger.PrivateRoom($"Removed {connection.ConnectionData.Username} ({connection.ConnectionData.ClientIP.ToString()}) from the privatechatroom queue"); } }
internal override void OnToolboxDisconnected(SocketClosedEventArgs e) { if (ConnectionQueue.ContainsKey(e.UniqueId)) { ConnectionQueue.Remove(e.UniqueId); } base.OnToolboxDisconnected(e); }
internal override void OnToolboxConnected(SocketConnectedEventArgs e) { if (!ConnectionQueue.ContainsKey(e.UniqueId)) { ConnectionQueue.Add(e.UniqueId, e.Address); } base.OnToolboxConnected(e); }
public virtual Connection GetConnection(EndPoint endPoint) { String lHost = endPoint.ToString(); lock (fSyncRoot) { ConnectionQueue lQueue = this.fCache.ContainsKey(lHost) ? (ConnectionQueue)this.fCache[lHost] : null; if (lQueue != null && lQueue.Count > 0) { return(lQueue.Dequeue()); } } return(this.GetNewConnection(endPoint)); }
/// <summary> /// Adds a specific connection to the connection queue. /// </summary> public void AddToQueue(ConnectionCore connection) { if (ConnectionQueue.Contains(connection)) { return; } ServerLogger.PrivateRoom($"Added {connection.ConnectionData.Username} ({connection.ConnectionData.ClientIP.ToString()}) to the private chatroom queue"); ConnectionQueue.Enqueue(connection); if (ConnectionQueue.Count >= 2) { CreatePrivateRoom(2); } }
/// <summary> /// Returns the connection matching the specified <paramref name="connectionKey"/> /// </summary> /// <param name="connectionKey">The unique identifier of the connection to retrieve.</param> /// <returns>The connection matching the specified connection key.</returns> public T Get(ConnectionKey connectionKey) { if (connectionKey != null) { var queuedConnection = ConnectionQueue.FirstOrDefault(c => c.Key.Equals(connectionKey)); if (!EqualityComparer <T> .Default.Equals(queuedConnection, default(T))) { return(queuedConnection); } else if (Connections.ContainsKey(connectionKey)) { return(Connections[connectionKey]); } } return(default(T)); }
/// <summary> /// Asynchronously adds the specified <paramref name="connection"/> to the manager. /// </summary> /// <remarks> /// If <see cref="Active"/> is fewer than <see cref="ConcurrentConnections"/>, the connection is connected immediately. Otherwise, it is queued. /// </remarks> /// <param name="connection">The connection to add.</param> /// <returns>A Task representing the asynchronous operation.</returns> public async Task AddAsync(T connection) { if (connection == null || connection.Key == null) { return; } if (Connections.Count < ConcurrentConnections) { if (Connections.TryAdd(connection.Key, connection)) { await TryConnectAsync(connection).ConfigureAwait(false); } } else { ConnectionQueue.Enqueue(connection); } }
/** * This method called by GCM plugin to set GCM register id */ public void OnRegisterId(string registerId) { Log("Registed id received: " + registerId); StringBuilder builder = InitConnectionData(_deviceInfo); builder.Append("&token_session="); AppendConnectionData(builder, "1"); builder.Append("&" + gcm.GetOS() + "_token="); AppendConnectionData(builder, registerId); builder.Append("&test_mode="); AppendConnectionData(builder, pushTestMode ? "2" : "0"); builder.Append("&locale="); AppendConnectionData(builder, _deviceInfo.Locale); ConnectionQueue.Enqueue(builder.ToString()); ProcessConnectionQueue(); }
// Accepts incoming connections if we are able private void AcceptPeerConnection() { // Create a wait handle array so we can cancel this thread if need be WaitHandle[] Wait = new[] { ReadyEvent, StopEvent }; while (0 == WaitHandle.WaitAny(Wait)) { // Check if stopped if (StopEvent.WaitOne(0)) { break; } // Lock our connection queue to prevent any race conditions lock (ConnectionQueue) { // Connection queue has entries, accept one if (ConnectionQueue.Count > 0) { // Dequeue the new peer in line var Connection = ConnectionQueue.Dequeue(); // Create a peer instance var Peer = new P2pPeer(this, Connection, PeerDirection.IN); // Handle this connection AddPeer(Peer); } // There are no entries in the connection queue else { // No peers in line, reset ready event ReadyEvent.Reset(); continue; } } } }
/// <summary> /// Creates and returns a private chatroom. /// </summary> public Chatroom CreatePrivateRoom(int joincount) { if (ConnectionQueue.Count < joincount) { return(null); } Chatroom privateRoom = new Chatroom(ServerManager.ChatroomManager.LastRoomId++); PrivateChatrooms.Add(privateRoom.ID, privateRoom); ServerManager.ChatroomManager.AddChatroom(privateRoom); for (int i = 0; i < joincount; i++) { ConnectionCore core = ConnectionQueue.Dequeue(); privateRoom.Join(core); core.SendMessage(new CreatePrivateRoomComposer(privateRoom)); core.SendMessage(new JoinChatroomComposer(privateRoom.ID, JoinState.JoinChatRoomOk)); } return(privateRoom); }
public async Task <IActionResult> Index([FromBody] HandShake.Request req) { var log = new LogModels.HttpRequest.Host.HandShake(); Log.AddChild(log); if (!Authorized) { return(Ok(new Unauthorized.Response { })); } HandShake.ResponseBase response = null; var que = new ConnectionQueue(SelfHost.sessionId); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.JoinBattleServer>(async(d) => { var lastBattle = new LastBattle(SelfHost.playerInfo.playerId); lastBattle.Model.lastExistedDate = DateTime.UtcNow; lastBattle.Model.matchId = d.matchId; await lastBattle.SaveAsync(); var token = evolib.Util.KeyGen.Get(32); var encryptionKey = new EncryptionKey(token); encryptionKey.Model.contents = evolib.Util.KeyGen.Get(32); await encryptionKey.SaveAsync(TimeSpan.FromMinutes(5)); var players = new List <JoinBattle.Response.Player>(); d.players.ForEach(p => { players.Add(new JoinBattle.Response.Player { playerId = p.playerId, groupNo = p.groupNo, side = p.side, }); }); response = new JoinBattle.Response() { ipAddr = d.ipAddr, port = d.port, joinPassword = d.joinPassword, token = token, newEncryptionKey = encryptionKey.Model.contents, mapId = d.mapId, rule = d.rule, matchId = d.matchId, matchType = d.matchType, players = players, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.MatchInfo>((d) => { var players = new List <MatchInfo.Response.Player>(); d.players.ForEach(p => { players.Add(new MatchInfo.Response.Player { playerId = p.playerId, side = p.side, groupNo = p.groupNo, }); }); response = new MatchInfo.Response() { matchId = d.matchId, matchType = d.matchType, players = players, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.ChangeBattlePhase>((d) => { response = new ChangeBattlePhase.Response() { phase = d.phase.ToString(), }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.ExecCommand>((d) => { response = new ExecCommand.Response() { command = d.command, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.RecievedFriendRequest>((d) => { response = new RecievedFriendRequest.Response() { playerId = d.playerId, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.UpdateFriends>((d) => { response = new UpdateFriends.Response(); }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.PremadeGroup>((d) => { var list = new List <PremadeGroup.Player>(); d.players.ForEach(p => { list.Add(new PremadeGroup.Player() { playerId = p.playerId, isLeader = p.isLeader, isInvitation = p.isInvitation, remainingSec = p.remainingSec, expirySec = p.expirySec, }); }); response = new PremadeGroup.Response() { players = list, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.PremadeGroupInvitation>((d) => { response = new PremadeGroupInvitation.Response() { playerId = d.playerId, remainingSec = d.remainingSec, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.DisconnectPlayer>((d) => { response = new DisconnectPlayer.Response() { players = d.players, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.Chat>((d) => { response = new Chat.Response() { type = d.type, playerId = d.playerId, playerName = d.playerName, text = d.text, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.BattleEntryState>((d) => { response = new BattleEntryState.Response() { state = d.state, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.OpenItems>((d) => { var items = new List <OpenItems.Response.Item>(); d.items.ForEach(item => { items.Add(new OpenItems.Response.Item { itemId = item.itemId, close = item.close, }); }); response = new OpenItems.Response() { items = items, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.UpdateAssets>((d) => { var inventory = new List <UpdateAssets.Response.Model>(); d.inventory.ForEach(model => { inventory.Add(new UpdateAssets.Response.Model { type = model.type, assetsId = model.assetsId, amount = model.amount, }); }); response = new UpdateAssets.Response() { inventory = inventory, }; }); que.RegisterProcessing <evolib.Kvs.Models.ConnectionQueueData.ClearChallenge>((d) => { response = new ClearChallenge.Response() { challengeIds = d.challengeIds, }; }); var startDate = DateTime.UtcNow; var responseTime = TimeSpan.FromSeconds(HandShake.NextResponseSeconds); var session = new Session(SelfHost.sessionId); while (true) { // Poke if (responseTime < (DateTime.UtcNow - startDate)) { response = new Poke.Response(); break; } // // On Request Aborted // if (HttpContext.RequestAborted.IsCancellationRequested) { await session.DeleteAsync(); await que.DeleteAsync(); log.Aborted = true; return(Ok()); } // // On Session Lost // if (!await session.ExistsAsync()) { return(Ok(new Close.Response() { reason = "LostSession", })); } //////////////////////////////////////////////////////////////// // // Fetch & Execute ConnectionQueue Data // //////////////////////////////////////////////////////////////// await que.DequeueAndProcessingAsync(); if (response != null) { break; } // // Sleep // //System.Threading.Thread.Sleep(1000); await Task.Delay(TimeSpan.FromSeconds(1)); } log.UpdateTTL = await session.SaveAsync(); response.limitPackageVersionLogin = evolib.VersionChecker.LimitPackageVersion(evolib.VersionChecker.CheckTarget.Login); response.limitPackageVersionMatchmake = evolib.VersionChecker.LimitPackageVersion(evolib.VersionChecker.CheckTarget.Matchmake); response.masterDataVersion = MasterData.Version; response.enabledMatchmake = evolib.VersionChecker.Get(evolib.VersionChecker.CheckTarget.EnabledMatchmake).Check(); response.opsNoticeCodes = evolib.OpsNoticeManager.Notices.Keys.ToList(); response.disabledMobileSuits = evolib.DisabledMobileSuit.DisabledThings(); return(Ok(response)); }
/// <summary> /// Disposes and removes all active and queued connections. /// </summary> public void RemoveAll() { ConnectionQueue.DequeueAndDisposeAll(); Connections.RemoveAndDisposeAll(); }