Esempio n. 1
0
 private static void OnOtherStatus(
     object sender,
     NetConnection connection,
     string output)
 {
     Console.WriteLine(output);
 }
 internal static void Execute(object msg, NetConnection conn)
 {
     Msg_CRC_StoryMessage _msg = msg as Msg_CRC_StoryMessage;
     if (null == _msg)
         return;
     try {
         string msgId = _msg.m_MsgId;
         ArrayList args = new ArrayList();
         for (int i = 0; i < _msg.m_Args.Count; i++) {
             switch (_msg.m_Args[i].val_type) {
                 case ArgType.NULL://null
                     args.Add(null);
                     break;
                 case ArgType.INT://int
                     args.Add(int.Parse(_msg.m_Args[i].str_val));
                     break;
                 case ArgType.FLOAT://float
                     args.Add(float.Parse(_msg.m_Args[i].str_val));
                     break;
                 default://string
                     args.Add(_msg.m_Args[i].str_val);
                     break;
             }
         }
         object[] objArgs = args.ToArray();
         GfxStorySystem.Instance.SendMessage(msgId, objArgs);
     } catch (Exception ex) {
         LogSystem.Error("Msg_CRC_StoryMessage throw exception:{0}\n{1}", ex.Message, ex.StackTrace);
     }
 }
Esempio n. 3
0
    public void DropClient(NetConnection connection, string message, params object[] args)
    {
        message = string.Format(message, args);

        Log(message);
        connection.Disconnect(message);
    }
 public NetReliableOrderedReceiver(NetConnection connection, int windowSize)
     : base(connection)
 {
     m_windowSize = windowSize;
     m_withheldMessages = new NetIncomingMessage[windowSize];
     m_earlyReceived = new NetBitVector(windowSize);
 }
Esempio n. 5
0
 private static void OnDisconnected(
     object sender,
     NetConnection connection,
     string output)
 {
     Console.WriteLine(
         "Disconnected: " + connection.RemoteUniqueIdentifier);
 }
Esempio n. 6
0
    void spawnOn(LidgrenGameObject go, NetConnection c)
    {
        NetOutgoingMessage msg = c.Peer.CreateMessage();
        msg.Write(LidgrenMessageHeaders.Spawn);
        msg.Write(go.Id);

        c.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, 1);
    }
Esempio n. 7
0
 public void RemoveClient(NetConnection nc) {
     try {
         Conns.Remove(nc.GetID());
         Logger.Log("SrvMgr: Removed " + nc.GetID());
     } catch (Exception e) {
         Logger.Log("SrvMgr: Failed to remove " + nc.GetID() + " (Already removed from collection?)");
     }
 }
 internal NetUnreliableSenderChannel(NetConnection connection, int windowSize)
 {
     m_connection = connection;
     m_windowSize = windowSize;
     m_windowStart = 0;
     m_sendStart = 0;
     m_receivedAcks = new NetBitVector(NetConstants.NumSequenceNumbers);
     m_queuedSends = new NetQueue<NetOutgoingMessage>(8);
 }
 internal void Reset()
 {
     m_incomingMessageType = NetIncomingMessageType.Error;
     m_readPosition = 0;
     m_receivedMessageType = NetMessageType.LibraryError;
     m_senderConnection = null;
     m_bitLength = 0;
     m_isFragment = false;
 }
Esempio n. 10
0
 internal static void Execute(object msg, NetConnection conn)
 {
     Msg_Pong pong_msg = msg as Msg_Pong;
     if (pong_msg == null) {
         return;
     }
     long time = TimeUtility.GetLocalMilliseconds();
     NetworkSystem.Instance.OnPong(time, pong_msg.send_ping_time, pong_msg.send_pong_time);
 }
Esempio n. 11
0
 void LoggedIn(NetConnection connection, LoginServer.Account account) {
     if (!database.HasKey(account.Id + "_chars")) socket.Send("OpenCreator", connection);
     else {
         string[] charNames;
         if (!TryGetCharacterNames(account.Id, out charNames)) {
             Debug.Log("Get char names failed.");
             return;
         }
         socket.Send("OpenCharacterList", connection, (string[])charNames, true);
     }
 }
Esempio n. 12
0
    public static LidgrenGameObject Spawn(int myId, int id, NetConnection con)
    {
        GameObject go = (GameObject)GameObject.Instantiate(Resources.Load("Player"), new Vector3(45, 10, 45), Quaternion.identity);
        LidgrenGameObject lgo = go.GetComponent<LidgrenGameObject>();

        lgo.Id = id;
        lgo.IsMine = myId == id;
        lgo.Connection = con;

        return lgo;
    }
 internal NetReliableSenderChannel(NetConnection connection, int windowSize)
 {
     m_connection = connection;
     m_windowSize = windowSize;
     m_windowStart = 0;
     m_sendStart = 0;
     m_receivedAcks = new NetBitVector(NetConstants.NumSequenceNumbers);
     m_storedMessages = new NetStoredReliableMessage[m_windowSize];
     m_queuedSends = new NetQueue<NetOutgoingMessage>(8);
     m_resendDelay = m_connection.GetResendDelay();
 }
Esempio n. 14
0
 public PlayerObject(int id, NetConnection connection, string name, int curBeat)
 {
     Connection = connection;
     Id = id;
     X = 0;
     Y = 0;
     VelocityX = 0;
     VelocityY = 0;
     Ready = false;
     Name = name;
     LastBeat = curBeat;
 }
Esempio n. 15
0
 internal static void Execute(object msg, NetConnection conn)
 {
     Msg_RC_ShakeHands_Ret ret_msg = msg as Msg_RC_ShakeHands_Ret;
     if (msg == null) {
         return;
     }
     NetworkSystem.Instance.WaitShakeHands = false;
     if (ret_msg.auth_result == Msg_RC_ShakeHands_Ret.RetType.SUCCESS) {
         LogSystem.Info("auth ok !!!");
         NetworkSystem.Instance.CanSendMessage = true;
         ClientModule.Instance.QueueAction(ClientModule.Instance.OnRoomServerConnected);
     } else {
         LogSystem.Info("auth failed !!!");
     }
 }
Esempio n. 16
0
    static NetworkPlayer FindPlayerByNetConnection(NetConnection con)
    {
        for (int i = 0; i < maxPlayers; i++ )
        {
            if(connectedPlayers[i] != null)
            {
                if(connectedPlayers[i].netConnection == con)
                {
                    return connectedPlayers[i];
                }
            }
        }

        return null;
    }
        public async void Login(string accountName, string password, NetConnection recipient)
        {
            //Ask validation from SQL.
            SqlCommand loginCommand = new SqlCommand("SELECT [Account_Password], [Account_Name] FROM [dbo].[Accounts] WHERE [Account_Name]='" + accountName + "'", m_SQLConnection);

            try
            {
                using (SqlDataReader reader = await loginCommand.ExecuteReaderAsync())
                {
                    NetOutgoingMessage newMsg = m_server.CreateMessage();

                    if (!reader.HasRows)
                    {
                        F3NetMessageLoginResult.ToNetMsg(NetErrorCode.ACCOUNT_NOT_FOUND, ref newMsg);
                    }
                    else
                    {

                        while (reader.Read())
                        {
                            string dbAccountName = reader["Account_Name"].ToString();
                            string dbAccountPassword = reader["Account_Password"].ToString();
                            if (dbAccountName == accountName && dbAccountPassword == password)
                            {
                                F3NetMessageLoginResult.ToNetMsg(NetErrorCode.OK, ref newMsg);
                            }
                            else if (dbAccountName == accountName && dbAccountPassword != password)
                            {
                                F3NetMessageLoginResult.ToNetMsg(NetErrorCode.INVALID_PASSWORD, ref newMsg);
                            }
                            else
                            {
                                F3NetMessageLoginResult.ToNetMsg(NetErrorCode.ACCOUNT_NOT_FOUND, ref newMsg);
                            }
                        }
                    }

                    m_server.SendMessage(newMsg, recipient, NetDeliveryMethod.ReliableUnordered);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("SQL ERROR :" + ex.Message + " ( " + ex.Number + ").");
            }
        }
            /// <summary>
            /// Send a message to all connections except one
            /// </summary>
            /// <param name="msg">The message to send</param>
            /// <param name="method">How to deliver the message</param>
            /// <param name="except">Don't send to this particular connection</param>
            /// <param name="sequenceChannel">Which sequence channel to use for the message</param>
            public void SendToAll(NetOutgoingMessage msg, NetConnection except, NetDeliveryMethod method, int sequenceChannel)
            {
                var all = this.Connections;
                if (all.Count <= 0)
                    return;

                if (except == null)
                {
                    SendMessage(msg, all, method, sequenceChannel);
                    return;
                }

                List<NetConnection> recipients = new List<NetConnection>(all.Count - 1);
                foreach (var conn in all)
                    if (conn != except)
                        recipients.Add(conn);

                if (recipients.Count > 0)
                    SendMessage(msg, recipients, method, sequenceChannel);
            }
            /// <summary>
            /// Send a message to a specific connection
            /// </summary>
            /// <param name="msg">The message to send</param>
            /// <param name="recipient">The recipient connection</param>
            /// <param name="method">How to deliver the message</param>
            /// <param name="sequenceChannel">Sequence channel within the delivery method</param>
            public NetSendResult SendMessage(NetOutgoingMessage msg, NetConnection recipient, NetDeliveryMethod method, int sequenceChannel)
            {
                if (msg == null)
                    throw new ArgumentNullException("msg");
                if (recipient == null)
                    throw new ArgumentNullException("recipient");
                if (sequenceChannel >= NetConstants.NetChannelsPerDeliveryMethod)
                    throw new ArgumentOutOfRangeException("sequenceChannel");

                NetException.Assert(
                    ((method != NetDeliveryMethod.Unreliable && method != NetDeliveryMethod.ReliableUnordered) ||
                    ((method == NetDeliveryMethod.Unreliable || method == NetDeliveryMethod.ReliableUnordered) && sequenceChannel == 0)),
                    "Delivery method " + method + " cannot use sequence channels other than 0!"
                );

                NetException.Assert(method != NetDeliveryMethod.Unknown, "Bad delivery method!");

                if (msg.m_isSent)
                    throw new NetException("This message has already been sent! Use NetPeer.SendMessage() to send to multiple recipients efficiently");
                msg.m_isSent = true;

                int len = NetConstants.UnfragmentedMessageHeaderSize + msg.LengthBytes; // headers + length, faster than calling msg.GetEncodedSize
                if (len <= recipient.m_currentMTU)
                {
                    Interlocked.Increment(ref msg.m_recyclingCount);
                    return recipient.EnqueueMessage(msg, method, sequenceChannel);
                }
                else
                {
                    // message must be fragmented!
                    if (recipient.m_status != NetConnectionStatus.Connected)
                        return NetSendResult.FailedNotConnected;
                    SendFragmentedMessage(msg, new NetConnection[] { recipient }, method, sequenceChannel);
                    return NetSendResult.Queued; // could be different for each connection; Queued is "most true"
                }
            }
Esempio n. 20
0
    void CreateCharacter(string playerName, NetConnection connection) {
        if (!InputValidator.LowercaseOnly(playerName)) return;
        LoginServer.Account account;
        if (!loginServer.TryGetAccount(connection, out account)) return;
        if (database.HasKey(playerName)) {
            socket.Send("NameTakenResponse", connection);
            return;
        }

        NetStream playerData = NetStream.New();
        playerData.WriteString(playerName);
        playerData.WriteInt(100);
        playerData.WriteVector3(Vector3.zero);

        ulong key;
        if (!database.TryAdd(playerName, playerData, out key)) return;
        if (!AddCharacterNameKey(key, account.Id)) {
            database.TryDelete(key);
            playerData.Release();
            return;
        }
        playerData.Position = 0;
        viewManager.CreateView(connection, "Player", playerData);
    }
Esempio n. 21
0
 public void OnPeerDisconnected(NetConnection conn)
 {
     OnDisconnected?.Invoke(conn.RemoteUniqueIdentifier);
     RemovePeerIfExist(conn.RemoteUniqueIdentifier);
     //Log.Debug(this, "[Server] Peer disconnected: " + conn.RemoteEndPoint);
 }
Esempio n. 22
0
    public void Disconnect(string reason)
    {
        client.Shutdown(reason);
        connection = null;

        Players = null;
    }
Esempio n. 23
0
 public static void AddNetConnection(this GameUser user, NetConnection con)
 {
     Console.WriteLine(user == null);
     userConnections[user] = con;
 }
Esempio n. 24
0
 public void SendMessage(NetOutgoingMessage message, NetConnection recipient,
                         NetDeliveryMethod method = NetDeliveryMethod.ReliableOrdered)
 {
     throw new NotImplementedException();
 }
Esempio n. 25
0
    private void HandleClientMessages()
    {
        NetIncomingMessage msg;

        while ((msg = client.ReadMessage()) != null)
        {
            switch (msg.MessageType)
            {
            case NetIncomingMessageType.StatusChanged:
                byte status = msg.ReadByte();
                switch (status)
                {
                case (byte)NetConnectionStatus.Connected:
                {
                    Debug.Log("Approved");
                    approvedConnection = true;
                }
                break;

                case (byte)NetConnectionStatus.InitiatedConnect:
                case (byte)NetConnectionStatus.RespondedConnect:
                    Debug.Log("Connection: " + status.ToString());
                    break;

                case (byte)NetConnectionStatus.Disconnected:
                case (byte)NetConnectionStatus.Disconnecting:
                    Debug.Log("Disconnecting: " + status.ToString());
                    break;
                }

                break;

            case NetIncomingMessageType.DiscoveryResponse:
                var success = msg.ReadBoolean();
                Debug.Log("Discovery Response: " + success);
                MyPlayerId = msg.ReadUInt16();
                if (success)
                {
                    ServerConnection = client.Connect(msg.SenderEndPoint);
                    Debug.Log(ServerConnection);
                }
                break;

            case NetIncomingMessageType.Data:
                var type = msg.ReadUInt16();
                switch (type)
                {
                //case (ushort)SpoopyMessageType.Approved:
                //	{
                //		Debug.Log("Approved");
                //		approvedConnection = true;
                //	}
                //	break;
                case (ushort)SpoopyMessageType.CreatePlayer:
                {
                    Debug.Log("Create Player");
                    ushort playerId = msg.ReadUInt16();
                    float  x        = msg.ReadFloat();
                    float  y        = msg.ReadFloat();
                    float  z        = msg.ReadFloat();

                    var player = GameObject.Instantiate(PlayerPrefab);
                    player.transform.position = new Vector3(x, y, z);
                    var controller = player.GetComponent <PlayerController>();
                    controller.PlayerId     = playerId;
                    controller.singlePlayer = false;

                    //These dam settings were subburn so I put them here instead of using the prefab values
                    controller.bulletSpawnDistance = 2f;
                    controller.Ammo = 100;

                    PlayerList.Add(controller);

                    if (playerId == MyPlayerId)
                    {
                        controller.ParentController = this;
                        playerCreated = true;
                    }
                }
                break;

                case (ushort)SpoopyMessageType.AuthoritativeUpdatePlayer:
                {
                    ushort playerId = msg.ReadUInt16();
                    float  x        = msg.ReadFloat();
                    float  y        = msg.ReadFloat();
                    float  z        = msg.ReadFloat();
                    float  rx       = msg.ReadFloat();
                    float  ry       = msg.ReadFloat();
                    float  rz       = msg.ReadFloat();

                    var player = PlayerList.FirstOrDefault(w => w.PlayerId == playerId);
                    if (player != null)
                    {
                        player.SetPositionAndRotation(new Vector3 {
                                x = x, y = y, z = z
                            }, new Vector3 {
                                x = rx, y = ry, z = rz
                            });
                        //player.transform.position = new Vector3 { x = x, y = y, z = z };
                        //player.transform.rotation = Quaternion.Euler(new Vector3 { x = rx, y = ry, z = rz });
                    }
                }
                break;

                case (ushort)SpoopyMessageType.UpdatePlayer:
                {
                    ushort playerId = msg.ReadUInt16();
                    float  x        = msg.ReadFloat();
                    float  y        = msg.ReadFloat();
                    float  z        = msg.ReadFloat();
                    float  rx       = msg.ReadFloat();
                    float  ry       = msg.ReadFloat();
                    float  rz       = msg.ReadFloat();

                    var player = PlayerList.FirstOrDefault(w => w.PlayerId == playerId);
                    if (player != null)
                    {
                        player.UpdatePositionAndRotation(new Vector3 {
                                x = x, y = y, z = z
                            },
                                                         new Vector3 {
                                x = rx, y = ry, z = rz
                            });
                    }
                }
                break;

                case (ushort)SpoopyMessageType.CreateBullet:
                {
                    ushort playerId = msg.ReadUInt16();
                    ushort bulletId = msg.ReadUInt16();
                    float  x        = msg.ReadFloat();
                    float  y        = msg.ReadFloat();
                    float  z        = msg.ReadFloat();
                    float  vx       = msg.ReadFloat();
                    float  vy       = msg.ReadFloat();
                    float  vz       = msg.ReadFloat();
                    float  rx       = msg.ReadFloat();
                    float  ry       = msg.ReadFloat();
                    float  rz       = msg.ReadFloat();

                    var bullet = GameObject.Instantiate(BulletPrefab);
                    bullet.transform.position = new Vector3(x, y, z);
                    var controller = bullet.GetComponent <BulletController>();
                    controller.PlayerId     = playerId;
                    controller.BulletId     = bulletId;
                    controller.singlePlayer = false;

                    controller.LifeTime = 5f;
                    controller.Vector   = new Vector3 {
                        x = vx, y = vy, z = vz
                    };
                    controller.transform.rotation = Quaternion.Euler(new Vector3 {
                            x = rx, y = ry, z = rz
                        });

                    if (MyPlayerId == playerId)
                    {
                        controller.UpdateBullet     = true;
                        controller.ParentController = this;
                    }

                    BulletList.Add(controller);
                }
                break;

                case (ushort)SpoopyMessageType.UpdateBullet:
                {
                    ushort bulletId = msg.ReadUInt16();
                    float  x        = msg.ReadFloat();
                    float  y        = msg.ReadFloat();
                    float  z        = msg.ReadFloat();

                    var target = BulletList.FirstOrDefault(w => w.BulletId == bulletId);
                    if (target != null)
                    {
                        target.transform.position += new Vector3(x, y, z);
                    }
                }
                break;

                case (ushort)SpoopyMessageType.DestroyBullet:
                {
                    ushort bulletId = msg.ReadUInt16();

                    var target = BulletList.FirstOrDefault(w => w.BulletId == bulletId);
                    if (target != null)
                    {
                        BulletList.Remove(target);
                        GameObject.Destroy(target.gameObject);
                    }
                }
                break;

                case (ushort)SpoopyMessageType.DestroyPlayer:
                {
                    ushort playerId = msg.ReadUInt16();

                    var target = PlayerList.FirstOrDefault(w => w.PlayerId == playerId);
                    if (target != null)
                    {
                        PlayerList.Remove(target);
                        GameObject.Destroy(target.gameObject);
                    }
                }
                break;
                }
                break;
            }

            client.Recycle(msg);
        }
    }
Esempio n. 26
0
 public override bool EqualsConnection(NetConnection connection)
 {
     return(peer.UserData() == ((EnetNetConnection)connection).peer.UserData());
 }
Esempio n. 27
0
 public static GameUser GetGameUser(this NetConnection con)
 => userConnections.Where(o => o.Value == con)?.FirstOrDefault().Key;
        public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
        {
            switch ((ComponentMessageType)message.MessageParameters[0])
            {
            case ComponentMessageType.SetVisible:
                visible = (bool)message.MessageParameters[1];
                break;

            case ComponentMessageType.SetSpriteByKey:
                SetSpriteByKey((string)message.MessageParameters[1]);
                break;
            }
        }
Esempio n. 29
0
 /// <summary>
 ///     Creates a new instance of a NetChannel.
 /// </summary>
 /// <param name="manager">The server this channel belongs to.</param>
 /// <param name="connection">The raw NetConnection to the remote peer.</param>
 internal NetChannel(NetManager manager, NetConnection connection, NetSessionId sessionId)
 {
     _manager    = manager;
     _connection = connection;
     SessionId   = sessionId;
 }
Esempio n. 30
0
        public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
        {
            switch ((ComponentMessageType)message.MessageParameters[0])
            {
            case ComponentMessageType.InventoryInformation:
                UnpackListing(message);
                break;

            case ComponentMessageType.InventoryUpdateRequired:
                if (UpdateRequired != null)
                {
                    UpdateRequired(this);
                }
                break;
            }
        }
Esempio n. 31
0
        public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
        {
            var type = (ComponentMessageType)message.MessageParameters[0];

            /*switch (type)
             * {
             *  case (ComponentMessageType.HealthStatus):
             *      Health = (float)message.MessageParameters[1];
             *      MaxHealth = (float)message.MessageParameters[2];
             *      if (GetHealth() <= 0) Die();
             *      break;
             * }*/
        }
Esempio n. 32
0
        /// <summary>
        /// Reads user info from connection hail-message.
        /// </summary>
        /// <param name="conn"></param>
        /// <returns></returns>
        public static string PeekHailUserInfo(this NetConnection conn)
        {
            var bytes = conn.RemoteHailMessage.PeekDataBuffer();

            return(Encoding.UTF8.GetString(bytes, 16, bytes.Length - 16));
        }
Esempio n. 33
0
 /// <summary>
 /// Reads client GUID from connection hail-message.
 /// </summary>
 /// <param name="conn"></param>
 /// <returns></returns>
 public static Guid PeekHailGuid(this NetConnection conn)
 {
     return(new Guid(conn.RemoteHailMessage.PeekBytes(16)));
 }
Esempio n. 34
0
 private void GetKeyRequest(string stringKey, NetRequest<ulong> request, NetConnection connection) {
     if (!connection.IsPeer && !connection.IsServer) return;
     ulong result;
     if (TryGetKey(stringKey, out result)) request.Result = result;
 }
Esempio n. 35
0
        public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
        {
            var type = (ComponentMessageType)message.MessageParameters[0];

            switch (type)
            {
            case (ComponentMessageType.AddAction):
                var typeName = (string)message.MessageParameters[1];
                var uid      = (uint)message.MessageParameters[2];
                AddAction(typeName, uid);
                break;

            case (ComponentMessageType.RemoveAction):
                var uid2 = (uint)message.MessageParameters[1];
                RemoveAction(uid2);
                break;

            case (ComponentMessageType.RequestActionList):
                UnpackFullListing(message);
                break;

            case (ComponentMessageType.GetActionChecksum):
                CheckFullUpdate((uint)message.MessageParameters[1]);
                break;

            case (ComponentMessageType.CooldownAction):
                var uidCd = (uint)message.MessageParameters[1];
                var secCd = (uint)message.MessageParameters[2];
                SetCooldown(uidCd, secCd);
                break;

            default:
                base.HandleNetworkMessage(message, sender);
                break;
            }
        }
Esempio n. 36
0
        public GameServer(int port, int maxPlayers) : base(MakeConfig(port, maxPlayers))
        {
            server    = new NetServer(base.Config);
            base.peer = server;
            base.tag  = "Server";

            this.MaxPlayers = maxPlayers;

            this.connectedPlayers = new List <Player>();
            this.idToPlayer       = new Dictionary <uint, Player>();
            this.remoteIDToPlayer = new Dictionary <long, HumanPlayer>();
            this.worldUploads     = new List <ActiveWorldUpload>();

            base.SetHandler(NetMessageType.Req_BasicServerInfo, (id, msg) =>
            {
                // Note: this message never arrives from the client if they are a host, as they already know everything about the world.

                // Send a little info about the server and the map...
                NetOutgoingMessage first = CreateBaseMapInfo();
                SendMessage(msg.SenderConnection, first, NetDeliveryMethod.ReliableOrdered);

                // Send player list.
                SendAllPlayerData(msg.SenderConnection);

                // The client should send back a response asking for full map info. (see below for response)
            });

            base.SetHandler(NetMessageType.Req_WorldChunks, (id, msg) =>
            {
                // Client has request for map/entity data to be sent.
                // TODO check that the client hasn't already requested this before.

                // Send map chunks.

                // Add a new world upload. TODO also upload entities.
                var upload = new ActiveWorldUpload(msg.SenderConnection, Main.Map.GetNumberOfNetChunks(), MaxChunksToUploadPerFrame);
                worldUploads.Add(upload);

                Trace($"Now starting to send {upload.TotalChunksToSend} chunks of map data...");
            });

            // Add status change listener.
            base.OnStatusChange += (conn, status, msg) =>
            {
                HumanPlayer player = GetPlayer(conn);
                switch (status)
                {
                case NetConnectionStatus.Connected:
                    // At this point, the HumanPlayer object has already been set up because it's connection was approved.
                    // Nothing to do here for now.

                    if (player == null)
                    {
                        Error($"Remote client has connected, but a player object is not associated with them... Did setup fail?");
                        break;
                    }

                    Log($"Client has connected: {player.Name} {(player.IsHost ? "(host)" : "")}");
                    Net.BroadcastConnect(player);

                    // Notify all clients that a new player has joined (apart from the host who already knows)
                    var newConnectMsg = CreateMessage(NetMessageType.Data_PlayerData, 32);
                    newConnectMsg.Write((byte)1);
                    newConnectMsg.Write(false);           // IsBot
                    player.WriteToMessage(newConnectMsg); // Other data such as IsHost, name etc.
                    SendMessageToAll(newConnectMsg, NetDeliveryMethod.ReliableSequenced, HostConnection);

                    break;

                case NetConnectionStatus.Disconnected:
                    // Player has left the game, bye!
                    // Remove the player associated with them.
                    if (player == null)
                    {
                        Error($"Remote client has disconnected, but a player object is not associated with them...");
                        break;
                    }

                    string text = msg.PeekString();

                    Log($"Client '{player.Name}' has disconnected: {text}");
                    Net.BroadcastDisconnect(player);

                    // Notify all clients that a player has left (apart from the host who already knows)
                    var disconnectMsg = CreateMessage(NetMessageType.Data_PlayerData, 32);
                    disconnectMsg.Write((byte)2);
                    disconnectMsg.Write(player.ID);
                    SendMessageToAll(disconnectMsg, NetDeliveryMethod.ReliableSequenced, HostConnection);

                    RemovePlayer(player);
                    break;
                }
            };

            // Add handlers.
            base.SetBaseHandler(NetIncomingMessageType.ConnectionApproval, (msg) =>
            {
                // TODO add check for number of players currently in the game.

                ulong hostKey = msg.ReadUInt64();
                bool isHost   = false;
                if (hostKey != 0)
                {
                    // This means that the client is claiming to be the local host.
                    // If so, the host key should be the same as the one on this object,
                    // which is generated when the server Start() method is called.
                    // Otherwise, there is either a serious bug or a hacking attempt.
                    if (hostKey != this.HostKey)
                    {
                        Warn($"Connecting client from {msg.SenderConnection} has claimed they are the host with host key {hostKey}, but this in the incorrect host key. Bug or impersonator?");
                    }
                    else
                    {
                        // Correct host key, they are the real host (or 1 in 18.4 quintillion chance).
                        isHost = true;
                    }
                }

                // Password (or empty string).
                string password = msg.ReadString();
                if (this.Password != null && password.Trim() != this.Password.Trim())
                {
                    msg.SenderConnection.Deny("Incorrect password");
                    return;
                }

                // Player name.
                string name = msg.ReadString();
                if (string.IsNullOrWhiteSpace(name))
                {
                    msg.SenderConnection.Deny("Invalid name");
                    return;
                }

                // Create player object for them.
                HumanPlayer p        = new HumanPlayer();
                p.IsHost             = isHost;
                p.Name               = name;
                p.ConnectionToClient = msg.SenderConnection;

                // Add player to the game. (gives them an Id and stuff)
                AddPlayer(p);

                if (isHost)
                {
                    // Flag them as the host connection.
                    HostConnection = msg.SenderConnection;
                }

                // Accept the connection, everything looks good!
                msg.SenderConnection.Approve();
            });
        }
Esempio n. 37
0
 /// <summary>
 /// Sends a network message to a particular client connection using a particular delivery method.
 /// None of the parameters may be null, and the connection must be valid (connected to this server).
 /// </summary>
 /// <param name="conn">The client connection to send to, may not be null and must be connected to this server.</param>
 /// <param name="msg">The message to send. Should contain at least 1 byte corresponding to it's type. See <see cref="NetPeerBase.CreateMessage(byte, int)"/> and <see cref="NetMessageType"/> for more info.</param>
 /// <param name="delivery">The delivery method to use. Most are self explanatory, see Lidgren documentation for more info.</param>
 /// <param name="channel">The network channel to send the data on. See Lidgren documentation for more info. If unsure, leave as default value.</param>
 public void SendMessage(NetConnection conn, NetOutgoingMessage msg, NetDeliveryMethod delivery, int channel = NetChannel.Default)
 {
     server.SendMessage(msg, conn, delivery, channel);
 }
Esempio n. 38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetStream"/> class that can be used for playing video files through the specified NetConnection object.
 /// </summary>
 /// <param name="connection">A NetConnection object.</param>
 /// <param name="peerId">Not available.</param>
 public NetStream(NetConnection connection, string peerId)
 {
     ValidationUtils.ArgumentNotNull(connection, "connection");
     _connection = connection;
     _client = this;
 }
Esempio n. 39
0
 public void SendDirectedComponentNetworkMessage(IEntity sendingEntity, uint netID,
                                                 NetDeliveryMethod method, NetConnection recipient,
                                                 params object[] messageParams)
 {
     throw new NotImplementedException();
 }
Esempio n. 40
0
 public static ClientState GetState(this NetConnection conn)
 {
     return(conn.Tag as ClientState);
 }
Esempio n. 41
0
 public static bool GameUserExist(this NetConnection con)
 => userConnections.Where(o => o.Value == con).Count() > 0;
Esempio n. 42
0
 public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
 {
     switch ((ComponentMessageType)message.MessageParameters[0])
     {
     case ComponentMessageType.GetSVars:
         HandleGetSVars(message);
         break;
     }
 }
Esempio n. 43
0
        private void ReadClientSteamAuthRequest(NetIncomingMessage inc, NetConnection senderConnection, out ulong clientSteamID)
        {
            clientSteamID = 0;
            if (!Steam.SteamManager.USE_STEAM)
            {
                DebugConsole.Log("Received a Steam auth request from " + senderConnection.RemoteEndPoint + ". Steam authentication not required, handling auth normally.");
                //not using steam, handle auth normally
                HandleClientAuthRequest(senderConnection, 0);
                return;
            }

            if (senderConnection == OwnerConnection)
            {
                //the client is the owner of the server, no need for authentication
                //(it would fail with a "duplicate request" error anyway)
                HandleClientAuthRequest(senderConnection, 0);
                return;
            }

            clientSteamID = inc.ReadUInt64();
            int authTicketLength = inc.ReadInt32();

            inc.ReadBytes(authTicketLength, out byte[] authTicketData);

            DebugConsole.Log("Received a Steam auth request");
            DebugConsole.Log("  Steam ID: " + clientSteamID);
            DebugConsole.Log("  Auth ticket length: " + authTicketLength);
            DebugConsole.Log("  Auth ticket data: " +
                             ((authTicketData == null) ? "null" : ToolBox.LimitString(string.Concat(authTicketData.Select(b => b.ToString("X2"))), 16)));

            if (senderConnection != OwnerConnection &&
                serverSettings.BanList.IsBanned(senderConnection.RemoteEndPoint.Address, clientSteamID))
            {
                return;
            }
            ulong steamID = clientSteamID;

            if (unauthenticatedClients.Any(uc => uc.Connection == inc.SenderConnection))
            {
                var steamAuthedClient = unauthenticatedClients.Find(uc =>
                                                                    uc.Connection == inc.SenderConnection &&
                                                                    uc.SteamID == steamID &&
                                                                    uc.SteamAuthStatus == Facepunch.Steamworks.ServerAuth.Status.OK);
                if (steamAuthedClient != null)
                {
                    DebugConsole.Log("Client already authenticated, sending AUTH_RESPONSE again...");
                    HandleClientAuthRequest(inc.SenderConnection, steamID);
                }
                DebugConsole.Log("Steam authentication already pending...");
                return;
            }

            if (authTicketData == null)
            {
                DebugConsole.Log("Invalid request");
                return;
            }

            unauthenticatedClients.RemoveAll(uc => uc.Connection == senderConnection);
            int nonce        = CryptoRandom.Instance.Next();
            var unauthClient = new UnauthenticatedClient(senderConnection, nonce, clientSteamID)
            {
                AuthTimer = 20
            };

            unauthenticatedClients.Add(unauthClient);

            if (!Steam.SteamManager.StartAuthSession(authTicketData, clientSteamID))
            {
                unauthenticatedClients.Remove(unauthClient);
                if (GameMain.Config.RequireSteamAuthentication)
                {
                    unauthClient.Connection.Disconnect(DisconnectReason.SteamAuthenticationFailed.ToString());
                    Log("Disconnected unauthenticated client (Steam ID: " + steamID + "). Steam authentication failed.", ServerLog.MessageType.ServerMessage);
                }
                else
                {
                    DebugConsole.Log("Steam authentication failed, skipping to basic auth...");
                    HandleClientAuthRequest(senderConnection);
                    return;
                }
            }

            return;
        }
Esempio n. 44
0
 public ActiveWorldUpload(NetConnection client, int toSendCount, int maxChunksPerFrame)
 {
     this.targetClient      = client;
     this.maxChunksPerFrame = maxChunksPerFrame;
     this.TotalChunksToSend = toSendCount;
 }
Esempio n. 45
0
    public void Connect(string host, int port)
    {
        client.Start();

        NetOutgoingMessage msg = client.CreateMessage();
        msg.Write(PlayerIdentityGenerator.PlayerIDToName(client.UniqueIdentifier));

        connection = client.Connect(host, port, msg);

        Players = new RemotePlayerSet();
    }
Esempio n. 46
0
 /// <summary>
 /// Sends a network message to all connected clients, with an optional excluded client.
 /// The message may not be null but <paramref name="except"/> may be null to send to all.
 /// See <see cref="HostConnection"/>.
 /// </summary>
 /// <param name="msg">The message to send. Should contain at least 1 byte corresponding to it's type. See <see cref="NetPeerBase.CreateMessage(byte, int)"/> and <see cref="NetMessageType"/> for more info.</param>
 /// <param name="delivery">The delivery method to use. Most are self explanatory, see Lidgren documentation for more info.</param>
 /// <param name="except">The (optional) client to exclude. All clients apart from the excluded client will receive the message. Often used with <see cref="HostConnection"/>.</param>
 /// <param name="channel">The network channel to send the data on. See Lidgren documentation for more info. If unsure, leave as default value.</param>
 public void SendMessageToAll(NetOutgoingMessage msg, NetDeliveryMethod delivery, NetConnection except = null, int channel = NetChannel.Default)
 {
     server.SendToAll(msg, except, delivery, 0);
 }
Esempio n. 47
0
 private void AddRequest(NetStream stream, NetRequest<ulong> request, NetConnection connection) {
     if (!connection.IsPeer && !connection.IsServer) return;
     request.Result = Add(stream);
 }
Esempio n. 48
0
 public void OnPeerConnected(NetConnection conn)
 {
     InsertOrUpdatePeer(conn.RemoteUniqueIdentifier, conn);
     OnConnected?.Invoke(conn.RemoteUniqueIdentifier);
 }
Esempio n. 49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetStream"/> class that can be used for playing video files through the specified NetConnection object.
 /// </summary>
 /// <param name="connection">A NetConnection object.</param>
 public NetStream(NetConnection connection) : this(connection, "connectToFMS")
 {
 }
Esempio n. 50
0
 public override bool EqualsConnection(NetConnection connection)
 {
     return(peer.UserData() == platform.CastToEnetNetConnection(connection).peer.UserData());
 }
Esempio n. 51
0
 internal NetChannelUnreliable(NetConnection connection) {
     Connection = connection;
     WriteUnreliableHeader();
 }
Esempio n. 52
0
 /// <summary>
 /// Initializes client state for given connection.
 /// </summary>
 /// <param name="conn"></param>
 public static void InitClientState(this NetConnection conn)
 {
     conn.Tag = new ClientState(PeekHailGuid(conn), PeekHailUserInfo(conn));
 }
Esempio n. 53
0
 private void GetStringRequest(string stringKey, NetRequest<NetStream> request, NetConnection connection) {
     if (!connection.IsPeer && !connection.IsServer) return;
     NetStream stream;
     if (TryGet(stringKey, out stream)) {
         stream.Position = stream.Size;
         request.Result = stream;
     }
 }
Esempio n. 54
0
        private static async Task QueryJavaServerAsync(string hostname, ushort port, PingServerDelegate pingCallback, ServerStatusDelegate statusCallBack)
        {
            IPEndPoint endPoint     = null;
            var        sw           = Stopwatch.StartNew();
            string     jsonResponse = null;

            try
            {
                var result = await ResolveHostnameAsync(hostname);

                if (!result.Success)
                {
                    statusCallBack?.Invoke(new ServerQueryResponse(false, "multiplayer.status.cannot_resolve", new ServerQueryStatus()
                    {
                        Delay   = sw.ElapsedMilliseconds,
                        Success = false,

                        EndPoint = null,
                        Address  = hostname,
                        Port     = port
                    }));

                    return;
                }

                bool waitingOnPing = true;
                using (TcpClient client = new TcpClient())
                {
                    await client.ConnectAsync(result.Result, port);

                    endPoint = client.Client.RemoteEndPoint as IPEndPoint;

                    if (client.Connected)
                    {
                        //conn = new NetConnection(Direction.ClientBound, client.Client);
                        //conn.LogExceptions = false;
                        using (var conn = new NetConnection(Direction.ClientBound, client.Client)
                        {
                            LogExceptions = true
                        })
                        {
                            long pingId = Rnd.NextUInt();

                            EventWaitHandle ar = new EventWaitHandle(false, EventResetMode.AutoReset);

                            conn.OnPacketReceived += (sender, args) =>
                            {
                                if (args.Packet is ResponsePacket responsePacket)
                                {
                                    jsonResponse = responsePacket.ResponseMsg;
                                    ar.Set();
                                }
                                else if (args.Packet is PingPacket pong)
                                {
                                    if (pong.Payload == pingId)
                                    {
                                        waitingOnPing = false;
                                        pingCallback?.Invoke(new ServerPingResponse(true, sw.ElapsedMilliseconds));
                                    }
                                    else
                                    {
                                        waitingOnPing = false;
                                        pingCallback?.Invoke(new ServerPingResponse(true, sw.ElapsedMilliseconds));
                                    }
                                }
                            };

                            bool connectionClosed = false;
                            conn.OnConnectionClosed += (sender, args) =>
                            {
                                connectionClosed = true;
                                ar.Set();
                            };

                            conn.Initialize();

                            conn.SendPacket(new HandshakePacket()
                            {
                                NextState       = ConnectionState.Status,
                                ServerAddress   = hostname,
                                ServerPort      = port,
                                ProtocolVersion = JavaProtocol.ProtocolVersion
                            });

                            conn.ConnectionState = ConnectionState.Status;

                            conn.SendPacket(new RequestPacket());

                            if (await WaitHandleHelpers.FromWaitHandle(ar, TimeSpan.FromMilliseconds(10000)) &&
                                !connectionClosed && jsonResponse != null)
                            {
                                long timeElapsed = sw.ElapsedMilliseconds;
                                //  Log.Debug($"Server json: " + jsonResponse);
                                var query = ServerQuery.FromJson(jsonResponse);

                                if (pingCallback != null)
                                {
                                    conn.SendPacket(new PingPacket()
                                    {
                                        Payload = pingId,
                                    });

                                    sw.Restart();
                                }

                                var r = new ServerQueryStatus()
                                {
                                    Delay         = timeElapsed,
                                    Success       = true,
                                    WaitingOnPing = pingCallback != null && !waitingOnPing,

                                    EndPoint = endPoint,
                                    Address  = hostname,
                                    Port     = port,

                                    Query = query
                                };

                                statusCallBack?.Invoke(new ServerQueryResponse(true, r));
                            }
                            else
                            {
                                statusCallBack?.Invoke(new ServerQueryResponse(false, "multiplayer.status.cannot_connect",
                                                                               new ServerQueryStatus()
                                {
                                    EndPoint = endPoint,
                                    Delay    = sw.ElapsedMilliseconds,
                                    Success  = false,

                                    /* Motd = motd.MOTD,
                                     * ProtocolVersion = motd.ProtocolVersion,
                                     * MaxNumberOfPlayers = motd.MaxPlayers,
                                     * Version = motd.ClientVersion,
                                     * NumberOfPlayers = motd.Players,*/

                                    Address       = hostname,
                                    Port          = port,
                                    WaitingOnPing = false
                                }));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (sw.IsRunning)
                {
                    sw.Stop();
                }

                Log.Error($"Could not get server query result! Exception: {ex.ToString()}");

                string msg = ex.Message;
                if (ex is SocketException)
                {
                    msg = $"multiplayer.status.cannot_connect";
                }

                statusCallBack?.Invoke(new ServerQueryResponse(false, msg, new ServerQueryStatus()
                {
                    Delay   = sw.ElapsedMilliseconds,
                    Success = false,

                    EndPoint = endPoint,
                    Address  = hostname,
                    Port     = port
                }));
            }
            finally
            {
                //conn?.Stop();
                //conn?.Dispose();
                //conn?.Dispose();
                //	client?.Close();
            }
        }
Esempio n. 55
0
 private void TryAddRequest(string stringKey, NetStream stream, NetRequest<ulong> request, NetConnection connection) {
     if (!connection.IsPeer && !connection.IsServer) return;
     ulong result;
     if (TryAdd(stringKey, stream, out result)) request.Result = result;
 }
 public void SendMessage(NetOutgoingMessage message, NetConnection recipient,
                         NetDeliveryMethod method = NetDeliveryMethod.ReliableOrdered)
 {
     m_netServer.SendMessage(message, recipient, method);
 }
 /// <summary>
 /// Send a message to a specific connection
 /// </summary>
 /// <param name="msg">The message to send</param>
 /// <param name="recipient">The recipient connection</param>
 /// <param name="method">How to deliver the message</param>
 public NetSendResult SendMessage(NetOutgoingMessage msg, NetConnection recipient, NetDeliveryMethod method)
 {
     return SendMessage(msg, recipient, method, 0);
 }
        /// <summary>
        /// Allows a component owned by this entity to send a message to a counterpart component on the
        /// counterpart entities on all clients.
        /// </summary>
        /// <param name="sendingEntity">Entity sending the message (also entity to send to)</param>
        /// <param name="family">Family of the component sending the message</param>
        /// <param name="method">Net delivery method -- if null, defaults to NetDeliveryMethod.ReliableUnordered</param>
        /// <param name="recipient">Client connection to send to. If null, send to all.</param>
        /// <param name="messageParams">Parameters of the message</param>
        public void SendDirectedComponentNetworkMessage(Entity sendingEntity, ComponentFamily family,
                                                        NetDeliveryMethod method,
                                                        NetConnection recipient, params object[] messageParams)
        {
            NetOutgoingMessage message = CreateEntityMessage();

            message.Write((byte)EntityMessage.ComponentMessage);
            message.Write(sendingEntity.Uid); //Write this entity's UID
            message.Write((byte)family);
            //Loop through the params and write them as is proper
            foreach (object messageParam in messageParams)
            {
                if (messageParam.GetType().IsSubclassOf(typeof(Enum)))
                {
                    message.Write((byte)NetworkDataType.d_enum);
                    message.Write((int)messageParam);
                }
                else if (messageParam is bool)
                {
                    message.Write((byte)NetworkDataType.d_bool);
                    message.Write((bool)messageParam);
                }
                else if (messageParam is byte)
                {
                    message.Write((byte)NetworkDataType.d_byte);
                    message.Write((byte)messageParam);
                }
                else if (messageParam is sbyte)
                {
                    message.Write((byte)NetworkDataType.d_sbyte);
                    message.Write((sbyte)messageParam);
                }
                else if (messageParam is ushort)
                {
                    message.Write((byte)NetworkDataType.d_ushort);
                    message.Write((ushort)messageParam);
                }
                else if (messageParam is short)
                {
                    message.Write((byte)NetworkDataType.d_short);
                    message.Write((short)messageParam);
                }
                else if (messageParam is int)
                {
                    message.Write((byte)NetworkDataType.d_int);
                    message.Write((int)messageParam);
                }
                else if (messageParam is uint)
                {
                    message.Write((byte)NetworkDataType.d_uint);
                    message.Write((uint)messageParam);
                }
                else if (messageParam is ulong)
                {
                    message.Write((byte)NetworkDataType.d_ulong);
                    message.Write((ulong)messageParam);
                }
                else if (messageParam is long)
                {
                    message.Write((byte)NetworkDataType.d_long);
                    message.Write((long)messageParam);
                }
                else if (messageParam is float)
                {
                    message.Write((byte)NetworkDataType.d_float);
                    message.Write((float)messageParam);
                }
                else if (messageParam is double)
                {
                    message.Write((byte)NetworkDataType.d_double);
                    message.Write((double)messageParam);
                }
                else if (messageParam is string)
                {
                    message.Write((byte)NetworkDataType.d_string);
                    message.Write((string)messageParam);
                }
                else if (messageParam is byte[])
                {
                    message.Write((byte)NetworkDataType.d_byteArray);
                    message.Write(((byte[])messageParam).Length);
                    message.Write((byte[])messageParam);
                }
                else
                {
                    throw new NotImplementedException("Cannot write specified type.");
                }
            }

            //Send the message
            if (recipient == null)
            {
                m_netServer.SendToAll(message, method);
            }
            else
            {
                m_netServer.SendMessage(message, recipient, method);
            }

            if (_messageProfiling)
            {
                var logger = IoCManager.Resolve <IMessageLogger>();
                logger.LogOutgoingComponentNetMessage(
                    (recipient == null) ? 0 : recipient.RemoteUniqueIdentifier,
                    sendingEntity.Uid,
                    family,
                    PackParamsForLog(messageParams));
            }
        }
Esempio n. 59
0
 public RemotePacketClient(NetConnection client, NetServer server)
 {
     Client = client;
     Server = server;
 }
Esempio n. 60
0
 public PlayerAndConnection(Player player, NetConnection connection)
 {
     Player     = player;
     Connection = connection;
 }