void OnConnectionStatusChanged(object sender, ConnectionEventArgs e) { if (listBoxInfo.InvokeRequired) { this.Invoke(new EventHandler<ConnectionEventArgs>(OnConnectionStatusChanged), sender, e); } else { listBoxInfo.Items.Add(string.Format("{0} {1}", e.Connection.Status, e.Connection.CalledPartyNumber)); } }
public void OnConnect(object sender, ConnectionEventArgs e) { Logger.Trace("Game-Client connected: {0}", e.Connection.ToString()); var gameClient = new GameClient(e.Connection); e.Connection.Client = gameClient; }
public static void OnDisconnect(object sender, ConnectionEventArgs e) { Logger.Trace("Client disconnected: {0}", e.Connection.ToString()); Universes.Remove(((GameClient) e.Connection.Client).GameUniverse); ClientUniverseMapper.Remove(((GameClient) e.Connection.Client)); }
private void ConnectionStateChanged(object sender, ConnectionEventArgs e) { _shell.DispatchOnUIThread(() => { IsConnected = e.State; IsRemote = e.Connection?.IsRemote ?? false; SelectedConnection = e.Connection?.Name; }); }
void RPCServerNew_OnConnect(object sender, ConnectionEventArgs e) { Log.Verbose("RPC-client connected: {0}", e.Connection.ToString()); var client = new RPCClient(e.Connection); e.Connection.Client = client; }
public void OnConnect(object sender, ConnectionEventArgs e) { Logger.Trace("Client connected: {0}", e.Connection.ToString()); var hausClient = new HAuSClient(e.Connection); e.Connection.Client = hausClient; }
private void MooNetServer_OnDisconnect(object sender, ConnectionEventArgs e) { var client = ((MooNetClient) e.Connection.Client); Logger.Trace("Client disconnected: {0}", e.Connection.ToString()); if (client.Account != null) client.Account.LoggedInClient = null; PlayerManager.PlayerDisconnected((MooNetClient)e.Connection.Client); }
public void OnDisconnect(object sender, ConnectionEventArgs e) { Logger.Trace("Client disconnected: {0}", e.Connection.ToString()); var toon = ((GameClient)e.Connection.Client).Player.Toon; toon.TimePlayed += DateTimeExtensions.ToUnixTime(DateTime.UtcNow) - toon.LoginTime; toon.SaveToDB(); GameManager.RemovePlayerFromGame((GameClient)e.Connection.Client); }
void GameServer_OnConnect(object sender, ConnectionEventArgs e) { Logger.Trace("Game-Client connected: {0}", e.Connection.ToString()); e.Connection.Client = new GameClient(e.Connection, GameUniverse); thread.Suspend(); clients.Add((GameClient)e.Connection.Client); thread.Resume(); }
protected virtual void OnConnectionReceived(ConnectionEventArgs e) { EventHandler<ConnectionEventArgs> handler = ConnectionReceived; if (handler != null) { ConnectionReceived(this, e); } }
public static void OnConnect(object sender, ConnectionEventArgs e) { Logger.Trace("Game-Client connected: {0}", e.Connection.ToString()); // atm, just creating a universe - though clients should be able to join existing ones. var universe = new Universe(); Universes.Add(universe); var gameClient = new GameClient(e.Connection,universe); e.Connection.Client = gameClient; }
void newConn_Disconnected(object sender, ConnectionEventArgs e) { try { Disconnected(sender, e); } catch (Exception ex) { // Console.WriteLine(ex.ToString()); } }
void MessageHub_ConnectionStateChange(object sender, ConnectionEventArgs e) { if (_inGetMessage > 0) return; if (e.Action == "Reconnected" || e.Action == "Connected") { FillDeltaMessage(); } }
void OnUserConnectionStateChanged(object sender, ConnectionEventArgs e) { if (e.State == ConnectionState.Connected) { var player = new Player { Name = "plr_" + DateTime.Now.Millisecond.ToString(CultureInfo.InvariantCulture) }; e.User["player"] = player; _service.AddEntity(player); Console.WriteLine("'{0}' connected", player.Name); } else if (e.State == ConnectionState.Disconnected) { var player = (Player)e.User["player"]; _service.RemoveEntity(player); Console.WriteLine("'{0}' disconnected", player.Name); } }
// we need this method instead of directly call OnConnectionStatusChanged // because of deadlock which can happen if we initiate the call ( pressing Call button). void OnConnectionStatusChangedInternal(object sender, ConnectionEventArgs e) { EventHandler<ConnectionEventArgs> d = new EventHandler<ConnectionEventArgs>(OnConnectionStatusChanged); if (e.Connection.Status == ConnectionStatus.Connected) { _currentIncommingConnection = e.Connection; if (!string.IsNullOrEmpty(_answerSoundFileName)) { ThreadPool.QueueUserWorkItem(SendFile, e.Connection); } } else { _currentIncommingConnection = null; } d.BeginInvoke(sender, e, null, null); }
// Handles the event that a connection is made private void OnServerConnection(object sender, ConnectionEventArgs e) { if (e.ConnectionEvent == ConnectionEvents.Connect) { // Lock the list so that only the networking thread affects it lock (this._clients) { if (!(this._clients.Contains(e.Connection))) { // Add to list and create event listener this._clients.Add(e.Connection); e.Connection.MessageReceived += new ConnectionMessageEventHandler(OnConnectionMessage); Message clientID = new Message("clientId"); clientID.AddField("id", this.clientIndex); e.Connection.SendMessage(clientID); this.clientIndex++; // Using the GUI thread make changes this.Dispatcher.Invoke( new Action( delegate() { this._clientsList.Items.Add(e.Connection); } )); } } } else if (e.ConnectionEvent == ConnectionEvents.Disconnect) { // Lock the list so that only the networking thread affects it lock (this._clients) { if (this._clients.Contains(e.Connection)) { // Clean up -- remove from list and remove event listener this._clients.Remove(e.Connection); e.Connection.MessageReceived -= new ConnectionMessageEventHandler(OnConnectionMessage); // Using the GUI thread make changes this.Dispatcher.Invoke( new Action( delegate() { this._clientsList.Items.Remove(e.Connection); } )); } } } }
internal static void RegisterHandlers(object source, ConnectionEventArgs args) { PacketHandler PRequestSubscriptionData = new PacketHandler(Process_RequestSubscriptionData); //PacketHandler P = new PacketHandler(Process_); //PacketHandler P = new PacketHandler(Process_); //PacketHandler P = new PacketHandler(Process_); //PacketHandler P = new PacketHandler(Process_); //PacketHandler P = new PacketHandler(Process_); //PacketHandler P = new PacketHandler(Process_); (source as IonTcpConnection). AddHandler(26, PacketHandlerPriority.DefaultAction, PRequestSubscriptionData); //AddHandler(, PacketHandlerPriority.DefaultAction, ). //AddHandler(, PacketHandlerPriority.DefaultAction, ). //AddHandler(, PacketHandlerPriority.DefaultAction, ). //AddHandler(, PacketHandlerPriority.DefaultAction, ). //AddHandler(, PacketHandlerPriority.DefaultAction, ) }
void OnAllPlayersConnect_Normal(Player sender, ConnectionEventArgs e) { if (!e.Connected) return; if (hasPlayerInfo(sender)) return; players.Add(new PlayerInfo(sender)); }
/// <summary> /// Starts this instance. /// </summary> public void Start() { StringBuilder sb = new StringBuilder(); _serialPort = new SerialPort(_panelLibrary.Port); _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived); _serialPort.BaudRate = _panelLibrary.BaudRate; if (_serialPort.BaudRate < 0) { sb.Length = 0; sb.AppendFormat("Warning: Baud rate: {0} must be greater than zero - exiting", _serialPort.BaudRate); Events.DoLog(this, sb.ToString()); return; } _serialPort.Parity = _panelLibrary.Parity; _serialPort.DataBits = _panelLibrary.DataBits; if (_serialPort.DataBits < 0) { sb.Length = 0; sb.AppendFormat("Warning: Data bits: {0} must be greater than zero - exiting", _serialPort.DataBits); Events.DoLog(this, sb.ToString()); return; } _serialPort.StopBits = _panelLibrary.StopBits; _serialPort.Handshake = _panelLibrary.HandShake; sb.Length = 0; sb.AppendFormat("Opening port {0}...", _panelLibrary.Port); Events.DoLog(this, sb.ToString()); try { _serialPort.Open(); ConnectionEventArgs e = new ConnectionEventArgs(); e.Port = _serialPort.PortName; e.BaudRate = _serialPort.BaudRate; e.Parity = _serialPort.Parity; e.DataBits = _serialPort.DataBits; e.StopBits = _serialPort.StopBits; e.Handshake = _serialPort.Handshake; sb.Length = 0; sb.AppendFormat("New connection on port {0},{1},{2},{3},{4},{5}", e.Port, e.BaudRate, e.DataBits, e.StopBits.ToString(), e.Parity.ToString(), e.Handshake.ToString()); e.Message = sb.ToString(); Events.DoConnect(this, e); } catch (Exception e) { Events.DoLog(this, e.ToString()); } }
private void MooNetServer_OnConnect(object sender, ConnectionEventArgs e) { Logger.Trace("MooNet-Client connected: {0}", e.Connection.ToString()); e.Connection.Client = new MooNetClient(e.Connection); }
/// <summary> /// Decode request package /// </summary> /// <param name="e"></param> /// <param name="package"></param> /// <returns></returns> public bool TryDecodePackage(ConnectionEventArgs e, out RequestPackage package) { package = null; string paramStr = Encoding.ASCII.GetString(e.Data); int index = paramStr.IndexOf("?d=", StringComparison.CurrentCultureIgnoreCase); string routeName = string.Empty; if (index != -1) { if (paramStr.StartsWith("route:", StringComparison.CurrentCultureIgnoreCase)) { routeName = paramStr.Substring(6, index - 6); } paramStr = paramStr.Substring(index, paramStr.Length - index); paramStr = HttpUtility.ParseQueryString(paramStr)["d"]; } var nvc = HttpUtility.ParseQueryString(paramStr); var param = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase); foreach (var key in nvc.AllKeys) { param[key] = nvc[key]; } if (param.ContainsKey("route")) { routeName = param["route"]; } //if (!param.ContainsKey("ssid")) { Interlocked.Increment(ref errorDropNum); return; } if (!param.ContainsKey("actionid")) { return(false); } if (!param.ContainsKey("msgid")) { return(false); } //sessionId of proxy server Guid proxySid; if (!param.ContainsKey("ssid") || !Guid.TryParse(param["ssid"], out proxySid)) { proxySid = Guid.Empty; } int actionid; if (!int.TryParse(param["actionid"], out actionid)) { return(false); } int msgid; if (!int.TryParse(param["msgid"], out msgid)) { return(false); } int userId; int.TryParse(param["uid"], out userId); string sessionId = param.ContainsKey("sid") ? param["sid"] : ""; package = new RequestPackage(msgid, sessionId, actionid, userId) { ProxySid = proxySid, IsProxyRequest = param.ContainsKey("isproxy"), RouteName = routeName, IsUrlParam = true, UrlParam = paramStr }; return(true); }
public void OnServiceConnect(object sender, ConnectionEventArgs args) { Console.WriteLine("Service Connected"); }
public void OnDisconnect(object sender, ConnectionEventArgs e) { Logger.Trace("Client disconnected: {0}", e.Connection.ToString()); GameManager.RemovePlayerFromGame((GameClient)e.Connection.Client); }
private void Controller_Connect(object sender, ConnectionEventArgs e) { }
// Update UI for current connection on event from any connection // (connection information is stored in the connection class) private void OnConnectionEvent(object sender, ConnectionEventArgs e) { SetConnectedUI(currentConnectionType.CurrentConnection.IsConnected); tbLog.Text = currentConnectionType.CurrentConnection.Log; }
/// <summary> /// Raises <see cref="ConnectionClosed"/>. /// </summary> /// <param name="args"></param> protected virtual void OnConnectionClosed(ConnectionEventArgs args) { EventHelper.Raise(ConnectionClosed, this, args); }
void connector_Connected(object sender, ConnectionEventArgs e) { serverID = e.ID; WarningDisconnectedSent = false; }
/// <summary> /// Raises <see cref="AddingConnection"/>. /// </summary> /// <param name="args"></param> protected virtual void OnAddingConnection(ConnectionEventArgs args) { EventHelper.Raise(AddingConnection, this, args); }
private static void CasparDevice_ConnectionStatusChanged(object sender, ConnectionEventArgs e) { Console.WriteLine("CasparCG Server connection is connected: " + e.Connected); }
/// <summary> /// Raises the <see cref="ConnectionClosed" /> event. /// </summary> /// <param name="e"> /// Contains the data for the event. /// </param> /// <remarks> /// The event will be raised on the thread on which the current instance was created. /// </remarks> protected virtual void OnConnectionClosed(ConnectionEventArgs e) { RaiseConnectionClosed(e); }
public void OnConnect(Player Player, ConnectionEventArgs args) { if (Player.Group.Permission < ServerSettings.GetSettingInt("StaffTimePermission")) { try { string picUri = "http://s3.amazonaws.com/MinecraftSkins/" + Player.Username + ".png"; WebRequest requestPic = WebRequest.Create(picUri); WebResponse responsePic = requestPic.GetResponse(); Image webImage = Image.FromStream(responsePic.GetResponseStream()); foreach (string s in Directory.GetFiles("bannedskins", "*.png")) { if (ZombieHelper.CompareImages(ZombieHelper.GetBitmap(s), (Bitmap)webImage)) { Player.Kick("This skin is not allowed to be used on this server!"); args.Cancel(); return; } } } catch { } //404 if invalid skin, do nothing } if (OmniBan.Contains(Player.Username.ToLower()) || OmniBan.Contains(Player.Ip + "")) { Player.Kick("You have been omnibanned from this server!"); args.Cancel(); return; } if (ZombieLevel != null) if (Player.Level != ZombieLevel) Player.Level = ZombieLevel; ExtraPlayerData l = new ExtraPlayerData(Player); ExtraPlayerData.Add(l); ZombieHelper.ResetPlayer(l); if (!ZombieRoundEnabled && !Voting) { if (AmountOfMinutesElapsed - 1 != 2) Player.SendMessage("[Zombie Survival]: " + Colors.red + "Round starts in " + -(AmountOfMinutesElapsed - 2) + ":" + (-(AmountOfSecondsElapsed % 60 - 60)).ToString("D2") + " minutes [Gamemode: " + ZombieHelper.GetGamemode(Gamemode) + "]"); } else if (!Voting) { l.Infected = true; l.Player.IsHeadFlipped = true; l.Player.DisplayName = Colors.red + "Undeaad"; Player.SendMessage("[Zombie Survival]: " + Colors.red + "A zombie game is in progress! You are infected as you joined before the game started. [Gamemode: " + ZombieHelper.GetGamemode(Gamemode) + "]"); } else { Player.SendMessage("[Zombie Survival]: " + Colors.red + "Vote on the next level by typing the level name!"); Player.SendMessage("[Zombie Survival]: " + Colors.red + "Options: " + LevelChoices[0] + "/" + LevelChoices[1] + "/random"); } }
protected void ConnectionReceived(object sender, ConnectionEventArgs e) { //Subscribe to connection events before before commencing. e.clientConnection.ConnectionNotify += ConnectionNotify; e.clientConnection.startConnection(); }
protected void OnConnectionEstablished(ConnectionEventArgs e) { ConnectionEstablished?.Invoke(this, e); }
protected override void OnConnectCompleted(object sender, ConnectionEventArgs e) { }
private void HandleLogin(byte[] message) { try { if (IsLoggedIn) return; byte version = message[0]; Username = enc.GetString(message, 1, 64).Trim(); _displayName = Username; string BanReason = null; bool banned = false; foreach (string line in File.ReadAllLines("bans/BanInfo.txt")) { if (Username == line.Split('`')[0]) { BanReason = line.Split('`')[1]; } } foreach (string line in Server.IPBans) { if (line == Ip) banned = true; } foreach (string line in Server.UsernameBans) { if (line == Username) banned = true; } if (banned) { if (BanReason == "No reason given.") { SKick("You are banned because " + BanReason); } else { SKick("You are banned!"); } } string verify = enc.GetString(message, 65, 32).Trim(); byte type = message[129]; if (!VerifyAccount(Username, verify)) return; if (Server.Verifying) IsVerified = false; else IsVerified = true; if (version != ServerSettings.Version) { SKick("Wrong Version!"); return; } try { Server.TempBan tb = Server.TempBansList.Find(ban => ban.name.ToLower() == Username.ToLower()); if (DateTime.Now > tb.allowed) { Server.TempBansList.Remove(tb); } else { SKick("You're still tempbanned!"); return; } } catch { } ConnectionEventArgs eargs = new ConnectionEventArgs(true); bool cancel = OnPlayerConnect.Call(this, eargs, OnAllPlayersConnect).Canceled; if (cancel) { Kick("Disconnected by canceled ConnectionEventArgs!"); } Gotos_Are_The_Devil: if (Server.PlayerCount >= ServerSettings.GetSettingInt("MaxPlayers") && !Server.VIPs.Contains(Username) && !Server.Devs.Contains(Username)) { int LoopAmount = 0; while (Server.PlayerCount >= ServerSettings.GetSettingInt("MaxPlayers")) { LoopAmount++; Thread.Sleep(1000); Packet pa = new Packet(); pa.Add(Packet.Types.MOTD); pa.Add(ServerSettings.Version); pa.Add("Waiting in queue, waiting for " + LoopAmount + " seconds", 64); pa.Add(Server.PlayerCount + " players are online right now out of " + ServerSettings.GetSettingInt("MaxPlayers") + "!", 64); pa.Add((byte)0); SendPacket(pa); } } //TODO Database Stuff Logger.Log("[System]: " + Ip + " logging in as " + Username + ".", System.Drawing.Color.Green, System.Drawing.Color.Black); try { Server.IRC.SendMessage(Username + " joined the game!"); } catch { } UniversalChat(Username + " joined the game!"); //WOM.SendJoin(Username); CheckDuplicatePlayers(Username); foreach (PlayerGroup g in PlayerGroup.Groups) if (g.Players.Contains(Username.ToLower())) Group = g; ExtraData.CreateIfNotExist("HasMarked", false); ExtraData.CreateIfNotExist("Mark1", new Vector3S()); ExtraData.CreateIfNotExist("Mark2", new Vector3S()); SendMotd(); IsLoading = true; IsLoggedIn = true; if (Level == null) Level = Server.Mainlevel; else Level = Level; ID = FreeId(); if (Server.PlayerCount >= ServerSettings.GetSettingInt("MaxPlayers")) goto Gotos_Are_The_Devil; //Gotos are literally the devil, but it works here so two players dont login at once UpgradeConnectionToPlayer(); short x = (short)((0.5 + Level.SpawnPos.x) * 32); short y = (short)((1 + Level.SpawnPos.y) * 32); short z = (short)((0.5 + Level.SpawnPos.z) * 32); Pos = new Vector3S(x, z, y); Rot = Level.SpawnRot; oldPos = Pos; oldRot = Rot; SendSpawn(this); SpawnThisPlayerToOtherPlayers(); UpdatePosition(true); SpawnOtherPlayersForThisPlayer(); SpawnBotsForThisPlayer(); IsLoading = false; //Load from Database Load(); foreach (string w in ServerSettings.GetSetting("welcomemessage").Split(new string[] { "<br>" }, StringSplitOptions.RemoveEmptyEntries)) SendMessage(w); } catch (Exception e) { Logger.LogError(e); } }
/// <summary> /// Raises <see cref="ClientDisconnected"/>. /// </summary> /// <param name="args"></param> private void OnClientDisconnected(ConnectionEventArgs args) { EventHelper.Raise(ClientDisconnected, this, args); }
private static void ServerConnected(object sender, ConnectionEventArgs args) { Console.WriteLine(args.IpPort + " connected"); }
/// <summary> /// Raised when a client disconnects from a broadcast provider. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void Connector_ClientDisconnected(object sender, ConnectionEventArgs args) { OnClientDisconnected(args); }
public void OnDisconnect(object sender, ConnectionEventArgs e) { Logger.Trace("Client disconnected: {0}", e.Connection.ToString()); Games.Remove(((GameClient)e.Connection.Client).Game); }
private void imap4Server1_ConnectionClosed(object sender, ConnectionEventArgs e) { PutLogMessage("Close Connection. Host: " + e.Connection.PeerIP); }
private void _discoveryProvider_ConnectionEstablished(object sender, ConnectionEventArgs e) { throw new NotImplementedException(); }
/// <summary> /// Raises the connect completed event. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> protected virtual void OnConnectCompleted(object sender, ConnectionEventArgs e) { }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnClientDisconnect(object sender, ConnectionEventArgs e) { _logger.Debug("Stratum client disconnected: {0}", e.Connection.ToString()); _minerManager.Remove(e.Connection); }
private void Connection_Disconnected(object sender, ConnectionEventArgs e) { var handler = this.disconnected; if(handler != null) handler(sender, e); }
private static void ClientConnected(object sender, ConnectionEventArgs args) { Console.WriteLine("Client connected: " + args.IpPort); }
/// <summary> /// Raises the received before event. /// </summary> /// <param name="e">E.</param> protected virtual void OnReceivedBefore(ConnectionEventArgs e) { }
/// <summary> /// Called when the connection is established. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Connector_ConnectionEstablished(object sender, ConnectionEventArgs e) { Connected(); }
public void OnDisconnect(Player Player, ConnectionEventArgs args) { bool Referee = false; long DateTimeAtStartOfRef = 0; foreach (ExtraPlayerData e in ExtraPlayerData) { if (e.Player.Username == Player.Username) { if (e.Referee) Referee = true; DateTimeAtStartOfRef = e.DateTimeAtStartOfRef; break; } } try { if (Referee) { long endTick = DateTime.Now.Ticks; long tick = 0; try { tick = endTick - DateTimeAtStartOfRef; } catch { } TextReader tr = new StreamReader("stafftime//" + Player.Username + ".time"); long amountOfTime = 0; try { amountOfTime = long.Parse(tr.ReadLine()); } catch { tr.Close(); return; } tr.Close(); amountOfTime += tick; try { TextWriter tw = new StreamWriter("stafftime//" + Player.Username + ".time", false); tw.WriteLine(amountOfTime); tw.Close(); } catch { } } } catch { } ExtraPlayerData.Remove(FindPlayer(Player.Username)); if (AmountInfected() <= 0 && AmountSurvived() > 0 && !Player.IsBot && ZombieRoundEnabled) { if (Server.Players.Count > 0) { Player.UniversalChat("[Zombie Survival]: " + Colors.red + ZombieHelper.InfectRandomPlayerReturn(ExtraPlayerData).Player.Username + " was chosen after the last infected disconnected!"); EndGame(); } else EndGame(true); } }
/// <summary> /// Called when the connection is closed. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Connector_ConnectionClosed(object sender, ConnectionEventArgs e) { ; }
void RPCServerNew_OnDisconnect(object sender, ConnectionEventArgs e) { Log.Verbose("RPC-client disconnected: {0}", e.Connection.ToString()); }
protected override void OnConnectCompleted(object sender, ConnectionEventArgs e) { Console.WriteLine("客户端IP:[{0}]已与服务器连接成功", e.Socket.RemoteEndPoint); base.OnConnectCompleted(sender, e); }
private void CloseConnection() { if (IsBot) return; ConnectionEventArgs eargs = new ConnectionEventArgs(false); OnPlayerDisconnect.Call(this, eargs); OnAllPlayersDisconnect.Call(this, eargs); GlobalDie(); Server.RemovePlayer(this); if (IsLoggedIn) { Logger.Log("[System]: " + Username + " Has DC'ed (" + lastPacket + ")", System.Drawing.Color.Gray, System.Drawing.Color.Black); try { Server.IRC.SendMessage("[System]: " + Username + " has disconnected"); } catch { } if (Server.PlayerCount > 0) Player.UniversalChat(Username + " has disconnected"); //WOM.SendLeave(Username); } IsLoggedIn = false; Server.Connections.Remove(this); Socket.Close(); Socket.Dispose(); }
private static void OnConnectionFailed(object sender, ConnectionEventArgs e) { LogUtility.LogMessage(String.Format("Connection failed")); SetState(ConnectionState.Disconnected); }
void OnConnected(object sender, ConnectionEventArgs e) { this._connection.MessageReceived += new ConnectionMessageEventHandler(OnMessageReceived); }
private void ConnectionManagerConnectionAdded(object sender, ConnectionEventArgs e) { // note: do not forget to remove events! e.Connection.MessageLogin += ConnectionMessageLogin; e.Connection.MessageEntityIn += Connection_MessageEntityIn; }
protected virtual void OnConnected(ConnectionEventArgs e) { Helpers.DebugInfo("Connection {0} connected.", e.Connection.Id); Connected?.Invoke(this, e); }
private void ConnectionClosedEventHandler(object sender, ConnectionEventArgs e) { this.connectionClosed = true; }
void GameServer_OnConnect(object sender, ConnectionEventArgs e) { Logger.Trace("Game-Client connected: {0}", e.Connection.ToString()); e.Connection.Client = new GameClient(e.Connection); }
/** * Linker objects call this when they are done, and we start * again if we need to */ public void CheckAndConnectHandler(object linker, EventArgs args) { ConnectionEventArgs cea = args as ConnectionEventArgs; DateTime now = DateTime.UtcNow; Linker new_linker = null; lock (_sync) { if (cea != null) { //This is a connection event. if (cea.Connection.MainType != ConnectionType.Leaf) { _last_non_leaf_connection_event = now; } } //Check in order of cheapness, so we can avoid hard work... bool time_to_start = (now - _last_retry >= _current_retry_interval); if ((_linker == null) && time_to_start && IsActive && NeedConnection) { //Now we double the retry interval. When we get a connection //We reset it back to the default value: _last_retry = now; _current_retry_interval += _current_retry_interval; _current_retry_interval = (_MAX_RETRY_INTERVAL < _current_retry_interval) ? _MAX_RETRY_INTERVAL : _current_retry_interval; //Get a random address to connect to: //Make a copy: object[] tas = _local.RemoteTAs.ToArray(); /* * Make a randomized list of TransportAddress objects to connect to: * This is a very nice algorithm. It is optimal in that it produces * a permutation of a list using N swaps and log(N!) bits * of entropy. */ for (int j = 0; j < tas.Length; j++) { //Swap the j^th position with this position: int i = _rnd.Next(j, tas.Length); if (i != j) { object temp_ta = tas[i]; tas[i] = tas[j]; tas[j] = temp_ta; } } /** * Make a Link to a remote node */ _linker = new Linker(_local, null, tas, "leaf", _local.Address.ToString()); new_linker = _linker; } else if (cea != null) { /* * This is the case that there was a non-leaf connection * or disconnection, BUT it is not yet time to start OR * there is current linker running OR we are not active OR * we don't need a connection * * In this case, we set the retry interval back to the default * value. This is because we only do the exponential back * off when there we can't seem to get connected when we try. * Clearly we are getting edges here, so there is no need * for the back-off. */ //Reset the connection interval to the default value: _current_retry_interval = _default_retry_interval; //We are not seeking another connection //log.Info("LeafConnectionOverlord : not seeking connection"); } //Check to see if it is time to trim. }//Drop the lock Trim(); /** * If there is a new linker, start it after we drop the lock */ if (new_linker != null) { new_linker.FinishEvent += this.LinkerFinishHandler; new_linker.Start(); } }