Beispiel #1
0
 public void SendMessageToAll(NetMessage msg, params NetConnection[] excluding)
 {
     foreach (var c in NetPeer.Connections)
     {
         if (!excluding.Contains(c))
         {
             msg.NetConnection = c;
             QueueNetMessage(msg);
         }
     }
 }
Beispiel #2
0
 void LidgrenServer_OnIncomingMessage(NetMessage message)
 {
     //if (message.Type == typeof(RequestNatIntroduction))
     //{
     //    var internalEndPoint = new IPEndPoint(IPAddress.Parse(ConfigConnectionElement.Ip), ConfigConnectionElement.Port);
     //    var externalEndPoint = new IPEndPoint(IPAddress.Parse(ConfigConnectionElement.ExternalIp), ConfigConnectionElement.Port);
     //    Log.Debug("Sending Nat Introduction Message");
     //    NetPeer.Introduce(internalEndPoint, externalEndPoint, message.NetConnection.RemoteEndpoint, message.NetConnection.RemoteEndpoint, "intro");
     //    return;
     //}
 }
Beispiel #3
0
        private void _server_OnIncomingMessage(NetMessage message)
        {
            if (message.Type == typeof(PlayerConnect))
            {
                Log.Info("Player Connected");
                var player = message.GetObject<Player>();

                foreach (var v in _players.Keys)
                {
                    var p = _players[v];
                    _server.SendMessage(new NetMessage() { Object = new PlayerConnect() { id = p.id, Name = p.Name, Position = p.Position, Rotation = p.Rotation, State = p.State } });
                }

                _players.Add(player.id, player);
                _server.SendMessageToAll(message, message.NetConnection);
            }
            else if (message.Type == typeof(PlayerMove))
            {
                var player = message.GetObject<Player>();
                if (_players.ContainsKey(player.id))
                {
                    _players[player.id] = player;
                    _server.SendMessageToAll(message, message.NetConnection);
                }

            }
            else if (message.Type == typeof(PlayerDisconnect))
            {
                Log.Info("Player Disconnected");
                var player = message.GetObject<Player>();
                if (_players.ContainsKey(player.id))
                {
                    _server.SendMessageToAll(message, message.NetConnection);
                    _players.Remove(player.id);
                }
            }
        }
        /// <summary>
        /// Run this when current ARUT arrives
        /// </summary>
        private void PostAcceptReliableMessage(NetMessage msg, int arut)
        {
            int seqChan = (int)msg.m_sequenceChannel;
            int relChanNr = seqChan - (int)NetChannel.ReliableUnordered;

            // step forward until next AllReliableReceivedUpTo (arut)
            bool nextArutAlreadyReceived = false;
            do
            {
                if (m_reliableReceived[relChanNr] == null)
                    m_reliableReceived[relChanNr] = new bool[NetConstants.NumSequenceNumbers];
                m_reliableReceived[relChanNr][arut] = false;
                arut++;
                if (arut >= NetConstants.NumSequenceNumbers)
                    arut = 0;
                nextArutAlreadyReceived = m_reliableReceived[relChanNr][arut];
                if (nextArutAlreadyReceived)
                {
                    // ordered?
                    if (seqChan >= (int)NetChannel.ReliableInOrder1)
                    {
                        // this should be a withheld message
                        int wmlidx = (int)seqChan - (int)NetChannel.ReliableUnordered;
                        bool foundWithheld = false;
                        foreach (IncomingNetMessage wm in m_withheldMessages[wmlidx])
                        {
                            if ((int)wm.m_sequenceChannel == seqChan && wm.m_sequenceNumber == arut)
                            {
                                // Found withheld message due for delivery
                                m_owner.LogVerbose("Releasing withheld message " + wm, this);
                                AcceptMessage(wm);
                                foundWithheld = true;
                                m_withheldMessages[wmlidx].Remove(wm);
                                break;
                            }
                        }
                        if (!foundWithheld)
                            throw new NetException("Failed to find withheld message!");
                    }
                }
            } while (nextArutAlreadyReceived);

            m_allReliableReceivedUpTo[relChanNr] = arut;
        }
Beispiel #5
0
        private void SendNetMessage(NetMessage msg)
        {
            // byte[] data = Illisian.UnityUtil.Compression.ByteArrays.Compress(Illisian.UnityUtil.Serialise.Binary.ObjectToByteArray(msg.Object));
            byte[] data = Illisian.UnityUtil.Serialise.Binary.ObjectToByteArray(msg.Object);

            NetOutgoingMessage sendMsg = NetPeer.CreateMessage();

            sendMsg.Write(data);
            if (!msg.UnconnectedMessage)
            {
                switch (msg.SequenceChannel)
                {
                    case 0: // Assume everything sent along channel 0 is encrypted
                        if (!sendMsg.Encrypt(_encryption))
                        {
                            Log.Critical("Unable to encrypt packet on Channel 0, please check the key that is being used.");
                        }
                        break;
                }
                NetPeer.SendMessage(sendMsg, msg.NetConnection, NetDeliveryMethod.ReliableOrdered, msg.SequenceChannel);
            }
            else
            {
                NetPeer.SendUnconnectedMessage(sendMsg, msg.DestinationIp, msg.DestinationPort);
            }
        }
Beispiel #6
0
        private void ProcessNetIncomingMessageData(NetIncomingMessage message, bool unconnected)
        {
            try
            {
                if (!unconnected)
                {
                    switch (message.SequenceChannel)
                    {
                        case 0: // Assume everything sent along channel 0 is encrypted
                            if (!message.Decrypt(_encryption))
                            {
                                Log.Critical("Unable to decrypt packet on Channel 0, please check the key that is being used.");
                            }
                            break;
                    }
                }

                //var data = Illisian.UnityUtil.Compression.ByteArrays.Decompress(message.ReadBytes(message.LengthBytes));
                var data = message.ReadBytes(message.LengthBytes);
                NetMessage _msg = new NetMessage();
                _msg.NetConnection = message.SenderConnection;
                _msg.Object = Illisian.UnityUtil.Serialise.Binary.ByteArrayToObject(data);
                _msg.SequenceChannel = message.SequenceChannel;
                _msg.UnconnectedMessage = unconnected;

                if (OnIncomingMessage != null)
                {
                    OnIncomingMessage(_msg);
                }
                else
                {
                    Log.Warn("Packets are being received but nothing is listening on the event hook");
                }
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Unable to Process Incoming Message :: Error Message: {0}", ex.Message));
            }
        }
Beispiel #7
0
        public void QueueNetMessage(NetMessage msg)
        {
            if (msg.Object == null)
            {
                Log.Critical("Attempting to send a empty message", msg);
                return;
            }
            if (!msg.UnconnectedMessage && msg.NetConnection == null)
            {
                Log.Critical("Attempting to send a message to nowhere", msg);
                return;
            }

            Monitor.Enter(_outgoingMessages);
            _outgoingMessages.Enqueue(msg);
            Monitor.Exit(_outgoingMessages);
        }
Beispiel #8
0
 public void SendMessage(NetMessage msg)
 {
     if (_client != null && _client.ConnectionStatus != NetConnectionStatus.Connected)
     {
         Connect();
     }
     Monitor.Enter(_pendingMessages);
     _pendingMessages.Enqueue(msg);
     Monitor.Exit(_pendingMessages);
 }
 public void HandleAdminMessage(NetMessage adminMsgType, NetIncomingMessage messageBody)
 {
     switch (adminMsgType)
     {
         case NetMessage.RequestAdminLogin:
             UserInterfaceManager.DisposeAllComponents<AdminPasswordDialog>(); //Remove old ones.
             UserInterfaceManager.AddComponent(new AdminPasswordDialog(new Size(200, 50), NetworkManager,
                                                                       ResourceManager)); //Create a new one.
             break;
         case NetMessage.RequestAdminPlayerlist:
             UserInterfaceManager.DisposeAllComponents<AdminPlayerPanel>();
             UserInterfaceManager.AddComponent(new AdminPlayerPanel(new Size(600, 200), NetworkManager,
                                                                    ResourceManager, messageBody));
             break;
         case NetMessage.RequestBanList:
             var banList = new Banlist();
             int entriesCount = messageBody.ReadInt32();
             for (int i = 0; i < entriesCount; i++)
             {
                 string ipAddress = messageBody.ReadString();
                 string reason = messageBody.ReadString();
                 bool tempBan = messageBody.ReadBoolean();
                 uint minutesLeft = messageBody.ReadUInt32();
                 var entry = new BanEntry
                                 {
                                     ip = ipAddress,
                                     reason = reason,
                                     tempBan = tempBan,
                                     expiresAt = DateTime.Now.AddMinutes(minutesLeft)
                                 };
                 banList.List.Add(entry);
             }
             UserInterfaceManager.DisposeAllComponents<AdminUnbanPanel>();
             UserInterfaceManager.AddComponent(new AdminUnbanPanel(new Size(620, 200), banList, NetworkManager,
                                                                   ResourceManager));
             break;
     }
 }
        private void ReceivedPong(double rtSeconds, NetMessage pong)
        {
            double now = NetTime.Now;
            m_lastPongReceived = now;
            if (pong != null)
            {
                ushort remote = pong.m_data.ReadUInt16();
                ushort local = NetTime.Encoded(now);
                int diff = local - remote - (int)(rtSeconds * 1000.0);
                if (diff < 0)
                    diff += ushort.MaxValue;
                m_remoteTimeOffset = diff; // TODO: slowly go towards? (m_remoteTimeOffset + diff) / 2;
                m_owner.LogVerbose("Got pong; roundtrip was " + (int)(rtSeconds * 1000) + " ms");
            }

            m_latencyHistory[2] = m_latencyHistory[1];
            m_latencyHistory[1] = m_latencyHistory[0];
            m_latencyHistory[0] = rtSeconds;
            m_currentAvgRoundtrip = ((rtSeconds * 3) + (m_latencyHistory[1] * 2) + m_latencyHistory[2]) / 6.0;

            m_ackMaxDelayTime = (float)(
                m_owner.m_config.m_maxAckWithholdTime * rtSeconds * m_owner.m_config.m_resendTimeMultiplier
            );
        }
Beispiel #11
0
 public void SendMessage(NetMessage msg)
 {
     QueueNetMessage(msg);
 }
Beispiel #12
0
 public void HandleAdminMessage(NetMessage adminMsgType, NetIncomingMessage messageBody)
 {
     switch (adminMsgType)
     {
         case NetMessage.RequestEntityDeletion:
             int entId = messageBody.ReadInt32();
             if (
                 IoCManager.Resolve<IPlayerManager>().GetSessionByConnection(messageBody.SenderConnection).
                     adminPermissions.isAdmin || true)
                 //TEMPORARY. REMOVE THE 'TRUE' LATER ON. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
             {
                 Entity delEnt = EntityManager.GetEntity(entId);
                 if (delEnt != null) EntityManager.DeleteEntity(delEnt);
             }
             break;
         case NetMessage.RequestAdminLogin:
             string password = messageBody.ReadString();
             if (password == IoCManager.Resolve<IConfigurationManager>().AdminPassword)
             {
                 LogManager.Log("Admin login: "******"Failed Admin login: "******" -> ' " + password + " '");
             break;
         case NetMessage.RequestAdminPlayerlist:
             if (
                 IoCManager.Resolve<IPlayerManager>().GetSessionByConnection(messageBody.SenderConnection).
                     adminPermissions.isAdmin)
             {
                 NetOutgoingMessage adminPlayerListMessage = IoCManager.Resolve<ISS14NetServer>().CreateMessage();
                 adminPlayerListMessage.Write((byte) NetMessage.RequestAdminPlayerlist);
                 adminPlayerListMessage.Write((byte) ClientList.Count);
                 foreach (
                     IPlayerSession plrSession in
                         ClientList.Keys.Select(
                             conn => IoCManager.Resolve<IPlayerManager>().GetSessionByConnection(conn)))
                 {
                     adminPlayerListMessage.Write(plrSession.name);
                     adminPlayerListMessage.Write((byte) plrSession.status);
                     adminPlayerListMessage.Write(plrSession.assignedJob.Name);
                     adminPlayerListMessage.Write(plrSession.connectedClient.RemoteEndPoint.Address.ToString());
                     adminPlayerListMessage.Write(plrSession.adminPermissions.isAdmin);
                 }
                 IoCManager.Resolve<ISS14NetServer>().SendMessage(adminPlayerListMessage,
                                                                  messageBody.SenderConnection,
                                                                  NetDeliveryMethod.ReliableOrdered);
             }
             else
             {
                 NetOutgoingMessage loginMessage = IoCManager.Resolve<ISS14NetServer>().CreateMessage();
                 loginMessage.Write((byte) NetMessage.RequestAdminLogin);
                 IoCManager.Resolve<ISS14NetServer>().SendMessage(loginMessage, messageBody.SenderConnection,
                                                                  NetDeliveryMethod.ReliableOrdered);
             }
             break;
         case NetMessage.RequestAdminKick:
             if (
                 IoCManager.Resolve<IPlayerManager>().GetSessionByConnection(messageBody.SenderConnection).
                     adminPermissions.isAdmin)
             {
                 string ipKick = messageBody.ReadString();
                 IPlayerSession kickSession = IoCManager.Resolve<IPlayerManager>().GetSessionByIp(ipKick);
                 if (kickSession != null)
                 {
                     IoCManager.Resolve<IPlayerManager>().EndSession(kickSession.connectedClient);
                     kickSession.connectedClient.Disconnect("Kicked by Administrator.");
                 }
             }
             break;
         case NetMessage.RequestAdminBan:
             if (
                 IoCManager.Resolve<IPlayerManager>().GetSessionByConnection(messageBody.SenderConnection).
                     adminPermissions.isAdmin)
             {
                 string ipBan = messageBody.ReadString();
                 IPlayerSession banSession = IoCManager.Resolve<IPlayerManager>().GetSessionByIp(ipBan);
                 if (banSession != null)
                 {
                     if (BanlistMgr.Singleton.IsBanned(ipBan)) return;
                     BanlistMgr.Singleton.AddBan(ipBan, "No reason specified.");
                     IoCManager.Resolve<IPlayerManager>().EndSession(banSession.connectedClient);
                     banSession.connectedClient.Disconnect("Banned by Administrator.");
                 }
             }
             break;
         case NetMessage.RequestBanList:
             if (
                 IoCManager.Resolve<IPlayerManager>().GetSessionByConnection(messageBody.SenderConnection).
                     adminPermissions.isAdmin)
             {
                 NetOutgoingMessage banListMessage = IoCManager.Resolve<ISS14NetServer>().CreateMessage();
                 banListMessage.Write((byte) NetMessage.RequestBanList);
                 banListMessage.Write(BanlistMgr.Singleton.banlist.List.Count);
                 foreach (BanEntry t in BanlistMgr.Singleton.banlist.List)
                 {
                     banListMessage.Write(t.ip);
                     banListMessage.Write(t.reason);
                     banListMessage.Write(t.tempBan);
                     int compare = t.expiresAt.CompareTo(DateTime.Now);
                     TimeSpan timeLeft = compare < 0 ? new TimeSpan(0) : t.expiresAt.Subtract(DateTime.Now);
                     var minutesLeft = (uint) Math.Truncate(timeLeft.TotalMinutes);
                     banListMessage.Write(minutesLeft);
                 }
                 IoCManager.Resolve<ISS14NetServer>().SendMessage(banListMessage, messageBody.SenderConnection,
                                                                  NetDeliveryMethod.ReliableOrdered);
             }
             break;
         case NetMessage.RequestAdminUnBan:
             if (
                 IoCManager.Resolve<IPlayerManager>().GetSessionByConnection(messageBody.SenderConnection).
                     adminPermissions.isAdmin)
             {
                 string ip = messageBody.ReadString();
                 BanlistMgr.Singleton.RemoveBanByIp(ip);
             }
             break;
     }
 }
		internal void CountDuplicateMessage(NetMessage msg)
		{
			m_duplicateMessagesRejected++;
			if (msg.m_type == NetMessageLibraryType.User)
				m_userDuplicateMessagesRejected++;
			NetConnectionStatistics window = GetCurrentWindow(NetTime.Now);
			if (window != null)
				window.CountDuplicateMessage(msg);
		}
		internal void CountMessageSent(NetMessage msg, int numBytes)
		{
			m_messagesSent++;
			if (msg.m_type == NetMessageLibraryType.User)
			{
				m_userMessagesSent++;
				m_userBytesSent += numBytes;
				m_userTypeMessagesSent[(int)msg.m_sequenceChannel]++;
			}

			NetConnectionStatistics window = GetCurrentWindow(NetTime.Now);
			if (window != null)
				window.CountMessageSent(msg, numBytes);
		}