Exemple #1
0
        public (UInt16, RoomStruct) BytesToRoomStruct(ref byte[] data)
        {
            RoomStruct room      = new RoomStruct();
            UInt16     errorCode = Constants.ROOM_CREATE_SUCCESS;

            if (data.Length + Constants.MESSAGE_BASE < PacketSizes.ROOM_CREATE_MIN)
            {
                return(Constants.ROOM_CREATE_FAILURE, room);
            }


            if (data.Length + Constants.MESSAGE_BASE > (PacketSizes.ROOM_CREATE_MAX))
            {
                return(Constants.ROOM_PASSWORD_BAD, room);
            }

            byte[] roomTypeBytes     = new byte[2];
            byte[] roomNameBytes     = new byte[15];
            byte[] roomPasswordBytes = new byte[15];

            try
            {
                Array.Copy(data, roomTypeBytes, 2);
            }
            catch
            {
                return(Constants.ROOM_CREATE_FAILURE, room);
            }

            room.roomType = BitConverter.ToUInt16(roomTypeBytes, 0);


            if (room.roomType == Constants.ROOM_TYPE_PRIVATE)
            {
                try
                {
                    Array.Copy(data, 2, roomNameBytes, 0, 15);
                }
                catch
                {
                    return(Constants.ROOM_NAME_BAD, room);
                }
                try
                {
                    Array.Copy(data, 17, roomPasswordBytes, 0, data.Length - 17);
                }
                catch
                {
                    return(Constants.ROOM_PASSWORD_BAD, room);
                }
            }

            if (room.roomType == Constants.ROOM_TYPE_PRIVATE)
            {
                room.roomName     = Encoding.ASCII.GetString(roomNameBytes);
                room.roomPassword = Encoding.ASCII.GetString(roomPasswordBytes);
            }

            return(errorCode, room);
        }
Exemple #2
0
        public (RoomStruct, UInt16) DecodeJoinPrivateRoom(ref byte[] data)
        {
            byte[] roomNameBytes = new byte[Constants.ROOM_NAME_LENGTH_MAX - 1];
            byte[] roomPasswordBytes;
            string password = "";

            Array.Copy(data, roomNameBytes, 15);

            string roomName = Encoding.ASCII.GetString(roomNameBytes);

            if (data.Length >= Constants.ROOM_NAME_LENGTH_MAX - 1)
            {
                roomPasswordBytes = new byte[data.Length - (Constants.ROOM_NAME_LENGTH_MAX - 1)];
                Array.Copy(data, Constants.ROOM_NAME_LENGTH_MAX - 1, roomPasswordBytes, 0, roomPasswordBytes.Length);
                password = Encoding.ASCII.GetString(roomPasswordBytes);
            }

            Console.WriteLine(roomName);

            RoomStruct room = new RoomStruct();

            room.roomType     = Constants.ROOM_TYPE_PRIVATE;
            room.roomName     = roomName;
            room.roomPassword = password;

            return(room, Constants.ROOM_PRIVATE_JOIN_SUCCESS);
        }
Exemple #3
0
        public Room CreatePrivateRoom(Client client, ref RoomStruct room)
        {
            room.roomName     = room.roomName.Trim('\0');
            room.roomPassword = room.roomPassword.Trim('\0');

            Room newRoom = new Room(client, room.roomType, client._clientId, room.roomName, room.roomPassword);

            return(newRoom);
        }
Exemple #4
0
        public UInt16 CheckRoomForErrors(ref RoomStruct room, Client c)
        {
            if (c._isInRoom)
            {
                return(Constants.USER_ALREADY_IN_ROOM);
            }

            if (CheckRoomType(room.roomType) != Constants.ROOM_TYPE_OK)
            {
                return(Constants.ROOM_TYPE_BAD);
            }

            if (room.roomType == Constants.ROOM_TYPE_PUBLIC)
            {
                return(Constants.ROOM_CREATE_SUCCESS);
            }


            UInt16 errorCode = CheckRoomName(room.roomName);

            if (errorCode == Constants.ROOM_NAME_IN_USE)
            {
                return(Constants.ROOM_NAME_IN_USE);
            }

            else if (errorCode == Constants.ROOM_NAME_BAD)
            {
                return(Constants.ROOM_NAME_BAD);
            }

            else if (CheckRoomPassword(room.roomPassword) != Constants.ROOM_PASSWORD_OK)
            {
                return(Constants.ROOM_PASSWORD_BAD);
            }

            return(Constants.ROOM_CREATE_SUCCESS);
        }
Exemple #5
0
        private static void RecieveCallback(IAsyncResult AR)
        {
            try
            {
                Socket socket = (Socket)AR.AsyncState;

                int recieved = socket.EndReceive(AR);

                if (recieved == 0)
                {
                    RemoveClient(ref socket, Constants.LOGOUT_FORCED);

                    return;
                }
                else if (recieved > 512)
                {
                    DisconnectUser(ref socket);
                    return;
                }

                counter++;

                UInt16 message_number = Messages.BAD_PACKET, packet_length = UInt16.MaxValue;
                int    clientId = socket.GetHashCode();

                //Packet handling recieving/sending
                byte[] dataBuff = new byte[recieved];
                Array.Copy(_buffer, dataBuff, recieved);

                //Breaking down buffer into segments
                byte[] message_number_bytes = new byte[2];
                byte[] packet_length_bytes  = new byte[2];
                byte[] data = new byte[Constants.SEND_BUFFER_SIZE];

                try
                {
                    data = new byte[recieved - Constants.MESSAGE_BASE];
                    if (recieved >= Constants.MESSAGE_BASE)
                    {
                        Array.Copy(dataBuff, message_number_bytes, 2);
                        Array.Copy(dataBuff, 2, packet_length_bytes, 0, 2);
                        Array.Copy(dataBuff, 4, data, 0, dataBuff.Length - 4);

                        //Turn bytes to usuable data
                        (message_number, packet_length) = serverHelper.BytesToMessageLength(message_number_bytes, packet_length_bytes);
                    }

                    //Print to console recieved data
                    serverHelper.PrintRecievedData(clientId, message_number, packet_length, ref data, ref dataBuff);
                }
                catch
                {
                    Console.WriteLine(clientId + " sent bad packet!");
                }

                UInt16 message_number_send = UInt16.MaxValue;
                UInt16 lengthToSend        = 0;
                byte[] dataToSendTemp      = new byte[512];

                #region MESSAGE HANDLING
                switch (message_number)
                {
                case Messages.SET_NAME_REQUEST:
                {
                    string temp_name = Encoding.ASCII.GetString(data);
                    UInt16 response  = _connectedClients[clientId].SetName(ref temp_name);

                    //Generating send data
                    {
                        message_number_send            = Messages.SET_NAME_RESPONSE;
                        (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, response);
                    }
                    break;
                }

                case Messages.LOGOUT:
                {
                    RemoveClient(ref socket, Constants.LOGOUT_NORMAL);
                    break;
                }

                case Messages.USER_ID_REQUEST:
                {
                    message_number_send            = Messages.USER_ID_RESPONSE;
                    (lengthToSend, dataToSendTemp) = packetHelper.IntToBytes(message_number_send, clientId);
                    break;
                }

                    #region ROOM_MESSAGES
                case Messages.ROOM_CREATE_REQUEST:
                {
                    if (data.Length <= Constants.MESSAGE_BASE + Constants.ROOM_NAME_LENGTH_MAX + Constants.ROOM_PASSWORD_LENGTH_MAX + 1)
                    {
                        (UInt16 errorCode, RoomStruct room) = packetHelper.BytesToRoomStruct(ref data);

                        message_number_send = Messages.ROOM_CREATE_RESPONSE;

                        if (_connectedClients[clientId]._isInRoom || _connectedClients[clientId]._findingRoom)
                        {
                            errorCode = Constants.ROOM_CREATE_FAILURE;
                        }
                        else
                        {
                            if (errorCode == Constants.ROOM_CREATE_FAILURE || errorCode == Constants.ROOM_NAME_BAD || errorCode == Constants.ROOM_PASSWORD_BAD)
                            {
                                Console.WriteLine("Room creation failed!");
                                (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, errorCode);
                            }

                            //Proceed
                            else if (errorCode == Constants.ROOM_CREATE_SUCCESS)
                            {
                                //reusing errorCode
                                errorCode = roomHelper.CheckRoomForErrors(ref room, _connectedClients[clientId]);

                                //if everything went good
                                if (errorCode == Constants.ROOM_CREATE_SUCCESS)
                                {
                                    message_number_send = Messages.ROOM_CREATE_RESPONSE;
                                    //Dont forget to check if user is already in a room, or owns one
                                    Console.WriteLine("------------------------------------------------------------");
                                    Console.WriteLine(clientId + " has created a room id: " + clientId);
                                    Console.WriteLine("Room Type: " + room.roomType + "\nRoom Name: " + room.roomName + "\nRoom Password: "******"------------------------------------------------------------");

                                    Room newRoom;

                                    if (room.roomType == Constants.ROOM_TYPE_PUBLIC)
                                    {
                                        newRoom = roomHelper.CreatePublicRoom(_connectedClients[clientId]);
                                        _connectedClients[clientId].EnteredRoom(ref newRoom);

                                        try
                                        {
                                            _publicRooms.Add(clientId, newRoom);
                                        }
                                        catch
                                        {
                                        }
                                    }
                                    else
                                    {
                                        newRoom = roomHelper.CreatePrivateRoom(_connectedClients[clientId], ref room);
                                        _connectedClients[clientId].EnteredRoom(ref newRoom);

                                        _privateRooms.Add(room.roomName, newRoom);
                                    }
                                }
                            }
                            (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, errorCode);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Invalid packet for room creation!");
                    }
                    break;
                }

                //gotta kick people off too
                case Messages.ROOM_ABANDON_REQUEST:
                {
                    Console.WriteLine("------------------------------------------------------------");
                    Console.WriteLine(clientId + " attempting to abandon room ID: " + clientId);
                    Console.WriteLine("------------------------------------------------------------");

                    message_number_send = Messages.ROOM_ABANDON_RESPONSE;
                    int recieved_id = BitConverter.ToInt32(data, 0);

                    int p2id = 0;

                    if (_connectedClients[clientId]._currentRoom.refClients[1] != null)
                    {
                        p2id = _connectedClients[clientId]._currentRoom.refClients[1]._clientId;
                    }

                    UInt16 errorCode = roomHelper.AbandonRoom(_connectedClients[clientId], ref recieved_id);

                    (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, errorCode);

                    if (errorCode == Constants.ROOM_ABANDONED_SUCCESS)
                    {
                        //telling player 2 that room has closed
                        if (p2id != 0)
                        {
                            try
                            {
                                SendDataRoomAbandoned(_connectedClients[p2id]._socket, p2id);
                            }
                            catch
                            {
                            }
                        }

                        Console.WriteLine("------------------------------------------------------------");
                        Console.WriteLine(clientId + " succesffully abandoned room ID: " + clientId);
                        Console.WriteLine("------------------------------------------------------------");
                    }
                    break;
                }

                case Messages.ROOM_JOIN_PUBLIC_ROOM_REQUEST:
                {
                    message_number_send = Messages.ROOM_JOIN_PUBLIC_ROOM_RESPONSE;
                    if (_connectedClients[clientId]._isInRoom)
                    {
                        (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_JOIN_FAILURE);
                    }
                    else
                    {
                        Console.WriteLine("People in queue: " + _clientQueue.Count);
                        Console.WriteLine(clientId + " added to queue. PUBLIC_ROOM");
                        _connectedClients[clientId]._findingRoom = true;

                        _clientQueue.Add(clientId);

                        (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_JOIN_SUCCESS);
                    }
                }
                break;

                case Messages.ROOM_JOIN_PRIVATE_ROOM_REQUEST:
                {
                    message_number_send = Messages.ROOM_JOIN_PRIVATE_ROOM_RESPONSE;
                    UInt16 errorCode;

                    if (_connectedClients[clientId]._isInRoom)
                    {
                        (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_PRIVATE_JOIN_FAILURE);
                    }
                    else
                    {
                        RoomStruct room = new RoomStruct();
                        //decode
                        {
                            errorCode         = Constants.ROOM_PRIVATE_JOIN_SUCCESS;
                            (room, errorCode) = packetHelper.DecodeJoinPrivateRoom(ref data);
                            room.roomName     = room.roomName.Trim('\0');
                            room.roomPassword = room.roomPassword.Trim('\0');
                            if (!_privateRooms.ContainsKey(room.roomName))
                            {
                                errorCode = Constants.ROOM_NAME_BAD;
                            }
                            else
                            {
                                if (_privateRooms[room.roomName]._roomPassword != room.roomPassword)
                                {
                                    errorCode = Constants.ROOM_PASSWORD_BAD;
                                }
                                else if (!_privateRooms[room.roomName]._isEmpty)
                                {
                                    errorCode = Constants.ROOM_FULL;
                                }
                            }
                        }

                        //send more data
                        if (errorCode == Constants.ROOM_PRIVATE_JOIN_SUCCESS)
                        {
                            //generate nice big msg
                            (lengthToSend, dataToSendTemp) = SendDataJoinedPrivateRoom(_privateRooms[room.roomName], _connectedClients[clientId]);
                        }
                        else
                        {
                            (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, errorCode);
                        }
                    }
                }
                break;

                case Messages.ROOM_CANCEL_FINDING_REQUEST:
                {
                    message_number_send = Messages.ROOM_CANCEL_FINDING_RESPONSE;
                    if (_connectedClients[clientId]._findingRoom)
                    {
                        Console.WriteLine(clientId + " removed from queue.");

                        _clientQueue.Remove(clientId);
                        _connectedClients[clientId].ClearStatus();

                        (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_CANCEL_FINDING_SUCCESS);
                    }
                    else
                    {
                        _connectedClients[clientId].ClearStatus();
                        (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_CANCEL_FINDING_FAILURE);
                    }
                }
                break;

                case Messages.ROOM_LEAVE_REQUEST:
                {
                    message_number_send = Messages.ROOM_LEAVE_RESPONSE;

                    {
                        if (_connectedClients[clientId]._isInRoom)
                        {
                            Console.WriteLine(clientId + " has left the room id: " + _connectedClients[clientId]._currentRoom._roomId);

                            int p1id = _connectedClients[clientId]._currentRoom._roomAdmin._clientId;

                            _connectedClients[clientId]._currentRoom.RemovePlayer2();
                            _connectedClients[clientId].ClearStatus();
                            (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_LEAVE_SUCCESS);

                            //Tell other player of room that player has left.
                            SendDataPlayerLeftRoom(p1id);
                        }
                        else
                        {
                            (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_LEAVE_FAILURE);
                        }
                    }

                    break;
                }

                case Messages.ROOM_CHANGE_MAP_REQUEST:
                {
                    UInt16 request = BitConverter.ToUInt16(data, 0);
                    message_number_send = Messages.ROOM_CHANGE_MAP_RESPONSE;

                    //checking if user is admin of a room
                    if (_connectedClients[clientId]._currentRoom._roomAdmin._clientId == clientId)
                    {
                        if (request <= MapManager._NumberOfMaps - 1)
                        {
                            (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_MAP_CHANGE_SUCCESS);
                            _connectedClients[clientId]._currentRoom.game.SetMap(request);
                            SendMapChangedData(_connectedClients[clientId]._currentRoom);
                        }
                        else
                        {
                            (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_MAP_CHANGE_FAILURE);
                        }
                    }
                    break;
                }

                case Messages.ROOM_CHANGE_DIFFICULTY_REQUEST:
                {
                    UInt16 request = BitConverter.ToUInt16(data, 0);
                    message_number_send = Messages.ROOM_CHANGE_DIFFICULTY_RESPONSE;

                    //check if user requesting change is admin
                    try
                    {
                        if (_connectedClients[clientId]._currentRoom._roomAdmin._clientId == clientId)
                        {
                            if (request <= Constants.ROOM_DIFFICULTY_HARD)
                            {
                                _connectedClients[clientId]._currentRoom.game.SetDifficulty(request);
                                (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_DIFFICULTY_CHANGE_SUCCESS);
                            }
                            else
                            {
                                _connectedClients[clientId]._currentRoom.game.SetDifficulty(Constants.ROOM_DIFFICULTY_EASY);
                                (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(message_number_send, Constants.ROOM_DIFFICULTY_CHANGE_FAILURE);
                            }
                            SendDifficultyChangedData(_connectedClients[clientId]._currentRoom);
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Welp, nice checking...");
                    }
                    break;
                }

                //Used in private rooms
                case Messages.ROOM_GAME_START_REQUEST:
                {
                    if (_connectedClients[clientId]._currentRoom._roomAdmin._clientId == clientId)
                    {
                        if (!_connectedClients[clientId]._currentRoom._isEmpty)
                        {
                            _connectedClients[clientId]._currentRoom.StartGame();
                        }
                        else
                        {
                            (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(Messages.ROOM_GAME_START_RESPONSE, Constants.ROOM_GAME_STARTED_FAILURE);
                        }
                    }
                    else
                    {
                        (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(Messages.ROOM_GAME_START_RESPONSE, Constants.ROOM_GAME_STARTED_FAILURE);
                    }
                    break;
                }

                case Messages.GAME_PLAYER_DIRECTION_CHANGE_REQUEST:
                {
                    message_number_send = Messages.GAME_PLAYER_DIRECTION_CHANGE_RESPONSE;
                    byte direction = data[0];

                    if (_connectedClients[clientId]._isInRoom && _connectedClients[clientId]._currentRoom.game._gameInProgress)
                    {
                        byte currentDir = 0;
                        bool player     = false;

                        if (_connectedClients[clientId]._currentRoom.refClients[0]._clientId == clientId)
                        {
                            currentDir = _connectedClients[clientId]._currentRoom.game.P1Direction;
                        }
                        else
                        {
                            currentDir = _connectedClients[clientId]._currentRoom.game.P2Direction;
                            player     = true;
                        }

                        if (Game.CheckValidDirection(currentDir, direction))
                        {
                            //player 1
                            if (!player)
                            {
                                _connectedClients[clientId]._currentRoom.game.P1Direction = direction;
                            }
                            else
                            {
                                _connectedClients[clientId]._currentRoom.game.P2Direction = direction;
                            }
                            (lengthToSend, dataToSendTemp) = packetHelper.ByteToBytes(message_number_send, direction);
                        }
                    }
                    break;
                }

                    #endregion
                    #region ADMIN_STUFF
                case Messages.ADMIN_LOGIN_REQUEST:
                {
                    string password = Encoding.ASCII.GetString(data);

                    if (password == Constants.ADMIN_LOGIN_PASSWORD)
                    {
                        (lengthToSend, dataToSendTemp)       = packetHelper.UInt16ToBytes(Messages.ADMIN_LOGIN_RESPONSE, Constants.ADMIN_LOGIN_SUCCESS);
                        _connectedClients[clientId]._isAdmin = true;
                    }
                    else
                    {
                        (lengthToSend, dataToSendTemp) = packetHelper.UInt16ToBytes(Messages.ADMIN_LOGIN_RESPONSE, Constants.ADMIN_LOGIN_FAILURE);
                    }

                    break;
                }

                case Messages.ADMIN_DUMP_USERS_TO_FILE:
                {
                    if (!_connectedClients[clientId]._isAdmin)
                    {
                        break;
                    }

                    Console.WriteLine("[ADMIN]Dump users to file.");

                    using (StreamWriter file = new StreamWriter("connected_clients.txt"))
                        foreach (var entry in _connectedClients)
                        {
                            file.WriteLine("[ ClientId: {0} User Name: {1} IP: {2} ]", entry.Key, entry.Value._userName, entry.Value._socket.RemoteEndPoint);
                        }

                    break;
                }

                case Messages.ADMIN_DUMP_GAMES_TO_FILE:
                {
                    if (!_connectedClients[clientId]._isAdmin)
                    {
                        break;
                    }

                    Console.WriteLine("[ADMIN]Dump games to file.");
                    Console.WriteLine("Public game count: " + _publicRooms.Count);
                    Console.WriteLine("Private game count: " + _privateRooms.Count);
                    using (StreamWriter file = new StreamWriter("public_games.txt"))
                        foreach (var entry in _publicRooms)
                        {
                            file.WriteLine("[ GameID: {0}\n Game Name: {1}]", entry.Key, entry.Value._roomName);
                        }

                    using (StreamWriter file = new StreamWriter("private_games.txt"))
                        foreach (var entry in _privateRooms)
                        {
                            file.WriteLine("[ GameID: {0}\n Game Name: {1}]", entry.Key, entry.Value._roomName);
                        }

                    break;
                }

                    #endregion
                case Messages.BAD_PACKET:
                {
                    lengthToSend = packetHelper.FillHeaderBlankData(Messages.BAD_PACKET, ref dataToSendTemp);
                    break;
                }

                default:
                    lengthToSend = packetHelper.FillHeaderBlankData(Messages.BAD_PACKET, ref dataToSendTemp);
                    break;
                }
                #endregion

                #region DATA_SEND
                byte[] dataToSend = new byte[lengthToSend];
                Array.Copy(dataToSendTemp, dataToSend, lengthToSend);

                if (lengthToSend > 0)
                {
                    serverHelper.PrintSendingData(clientId, message_number_send, lengthToSend, ref dataToSend);
                    try
                    {
                        socket.BeginSend(dataToSend, 0, dataToSend.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
                    }
                    catch
                    {
                    }
                }
                #endregion
                socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), socket);
            }

            catch (SocketException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }