Exemplo n.º 1
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                Socket clientSocket = (Socket)ar.AsyncState;
                clientSocket.EndReceive(ar);

                //Transform the array of bytes received from the user into an
                //intelligent form of object Data
                Data msgReceived = new Data(byteData);

                //We will send this object in response the users request
                Data msgToSend = new Data();

                byte [] message;
                string clientName;

                //If the message is to login, logout, or simple text message
                //then when send to others the type of the message remains the same
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName = msgReceived.strName;

                switch (msgReceived.cmdCommand)
                {
                    case Command.Login:

                        //When a user logs in to the server then we add her to our
                        //list of clients

                        ClientInfo clientInfo = new ClientInfo();
                        clientInfo.socket = clientSocket;
                        clientInfo.strName = msgReceived.strName;

                        clientList.Add(clientInfo);

                        //Set the text of the message that we will broadcast to all users
                        msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                        break;

                    case Command.Logout:

                        //When a user wants to log out of the server then we search for her
                        //in the list of clients and close the corresponding connection

                        int nIndex = 0;
                        foreach (ClientInfo client in clientList)
                        {
                            if (client.socket == clientSocket)
                            {
                                clientList.RemoveAt(nIndex);
                                break;
                            }
                            ++nIndex;
                        }

                        clientSocket.Close();

                        msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the room>>>";
                        break;

                    case Command.Message:

                        //Set the text of the message that we will broadcast to all users
                        msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                        msgToSend.clientName = msgReceived.clientName;
                        break;

                    case Command.List:

                        //Send the names of all users in the chat room to the new user
                        msgToSend.cmdCommand = Command.List;
                        msgToSend.strName = null;
                        msgToSend.strMessage = null;
                        msgToSend.clientName = null;

                        //Collect the names of the user in the chat room
                        foreach (ClientInfo client in clientList)
                        {
                            //To keep things simple we use asterisk as the marker to separate the user names
                            msgToSend.strMessage += client.strName + "*";
                        }

                        message = msgToSend.ToByte();

                        //Send the name of the users in the chat room
                        clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                new AsyncCallback(OnSend), clientSocket);
                        break;
                }

                if (msgToSend.cmdCommand != Command.List)   //List messages are not broadcasted
                {
                    message = msgToSend.ToByte();
                    if (msgToSend.clientName != null)
                        clientName = msgToSend.clientName;
                    else
                        clientName = null;

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.socket != clientSocket ||
                            msgToSend.cmdCommand != Command.Login)
                        {
                            //Send the message to all users
                            if (clientName == null)
                            {
                                clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                                            new AsyncCallback(OnSend), clientInfo.socket);
                            }
                            else
                            {
                                if(clientInfo.strName==clientName)
                                {
                                    clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                                                new AsyncCallback(OnSend), clientInfo.socket);
                                }
                            }
                        }
                    }

                    //txtLog.Text += msgToSend.strMessage + "\r\n";
                    //MessageBox.Show(msgToSend.strMessage);
                }

                //If the user is logging out then we need not listen from her
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    //Start listening to the message send by the user
                    clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSserverTCP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 2
0
        private void тестToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _testResult = 0;
            _flagTest = 0;

            Data msgToSend = new Data();
            msgToSend.cmdCommand = Command.TestPackageSend;
            msgToSend.strName = null;
            msgToSend.strMessage = null;
            for (int i = 0; i < _testNum; i++)
            {
                Thread.Sleep(1);
                SendToAll(msgToSend.ToByte());
            }

            msgToSend.cmdCommand = Command.TestPackageRecieve;
            SendToAll(msgToSend.ToByte());
        }
Exemplo n.º 3
0
        private void OnReceive(IAsyncResult ar)
        {
            try
                {
                    IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                    EndPoint epSender = (EndPoint)ipeSender;

                    serverSocket.EndReceiveFrom(ar, ref epSender);

                    //Transform the array of bytes received from the user into an
                    //intelligent form of object Data
                    Data msgReceived = new Data(byteData);

                    //We will send this object in response the users request
                    Data msgToSend = new Data();

                    byte[] message;

                    //If the message is to login, logout, or simple text message
                    //then when send to others the type of the message remains the same
                    msgToSend.cmdCommand = msgReceived.cmdCommand;
                    msgToSend.strName = msgReceived.strName;

                    switch (msgReceived.cmdCommand)
                    {
                        case Command.Login:

                            //When a user logs in to the server then we add her to our
                            //list of clients

                            ClientInfo clientInfo = new ClientInfo();
                            clientInfo.endpoint = epSender;
                            clientInfo.strName = msgReceived.strName;

                            clientList.Add(clientInfo);

                            //Set the text of the message that we will broadcast to all users
                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                            players.Add(new Player(new Point(10, 10), Color.DarkGray, msgReceived.strName));
                            _isMove = true;
                            //Invalidate();
                            break;

                        case Command.Logout:

                            //When a user wants to log out of the server then we search for her
                            //in the list of clients and close the corresponding connection

                            int nIndex = 0;
                            foreach (ClientInfo client in clientList)
                            {
                                if (client.endpoint.ToString() == epSender.ToString())
                                {
                                    clientList.RemoveAt(nIndex);
                                    players.RemoveAt(nIndex);
                                    break;
                                }
                                ++nIndex;
                            }

                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the room>>>";
                            //Left_Game(msgReceived.strName);                                                   // Нужна ли эта функция??
                            break;

                        case Command.Message:

                            //Set the text of the message that we will broadcast to all users

                            msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                            break;

                        case Command.Draw:
                            if (!_isUserConnect)
                            {
                                _isUserConnect=true;
                                // Draw Player Coordinat on the screen

                                switch (msgReceived.byteColor)
                                {
                                    case 0: color = Color.Red;
                                        break;
                                    case 1: color = Color.Yellow;
                                        break;
                                    case 2: color = Color.Green;
                                        break;
                                    case 3: color = Color.Blue;
                                        break;
                                    case 4: color = Color.Magenta;
                                        break;
                                }
                                int userPosition = GetUser(msgReceived.strName);

                                players[userPosition].position = new Point(msgReceived.posX,msgReceived.posY);
                                players[userPosition].color = color;

                                msgToSend.posX = Convert.ToByte(players[userPosition].position.X);
                                msgToSend.posY = Convert.ToByte(players[userPosition].position.Y);
                                msgToSend.byteColor = msgReceived.byteColor;

                                //msgToSend.strMessage = msgReceived.strName + ": " + getPoints[0].ToString() + " " + getPoints[1].ToString() + " " + getPoints[3];
                                _isUserConnect=false;
                                _isMove = true;
                            }
                            break;

                        case Command.List:

                            //Send the names of all users in the chat room to the new user
                            msgToSend.cmdCommand = Command.List;
                            msgToSend.strName = null;
                            msgToSend.strMessage = null;

                            //Collect the names of the user in the chat room
                            foreach (ClientInfo client in clientList)
                            {
                                //To keep things simple we use asterisk as the marker to separate the user names
                                msgToSend.strMessage += client.strName + "*";
                            }

                            message = msgToSend.ToByte();

                            //Send the name of the users in the chat room
                            serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                                    new AsyncCallback(OnSend), epSender);
                            break;
                    }

                    if (msgToSend.cmdCommand != Command.List)   //List messages are not broadcasted
                    {
                        message = msgToSend.ToByte();

                        foreach (ClientInfo clientInfo in clientList)
                        {
                            if (clientInfo.endpoint.ToString() != epSender.ToString() ||
                                msgToSend.cmdCommand != Command.Login)
                            {
                                //Send the message to all users
                                serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                                    new AsyncCallback(OnSend), clientInfo.endpoint);
                            }
                        }

                        if(msgToSend.strMessage!=null)
                            txtLog.Text += msgToSend.strMessage + "\r\n";
                    }

                    //If the user is logging out then we need not listen from her
                    if (msgReceived.cmdCommand != Command.Logout)
                    {
                        //Start listening to the message send by the user
                        serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender,
                            new AsyncCallback(OnReceive), epSender);
                    }
                    if (msgReceived.cmdCommand == Command.Logout)
                    {
                        //Start receiving data
                        serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length,
                            SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
        }
Exemplo n.º 4
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                //We will send this object in response the users request
                Data msgToSend = new Data();

                Socket currentClientSocket;
                currentClientSocket = (Socket)ar.AsyncState;

                if (!SocketConnected(currentClientSocket))
                {
                    String name = RemoveClient(currentClientSocket);
                    msgToSend.strMessage = "<<<" + name + " has left the room>>>";

                    SendToAll(msgToSend.ToByte());
                    return;
                }
                int res = currentClientSocket.EndReceive(ar);

                ClientInfo currentClient = null;

                foreach (ClientInfo i in clientList) {
                    if (i.socket == currentClientSocket) {
                        currentClient = i;
                        break;
                    }
                }

                if (currentClient == null) {
                    MessageBox.Show("Viktor is going to change his gender now", "Viktor allerts us!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //Transform the array of bytes received from the user into an
                //intelligent form of object Data
                Data msgReceived = new Data(currentClient.byteData);

                byte [] message;

                //If the message is to login, logout, or simple text message
                //then when send to others the type of the message remains the same
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName = msgReceived.strName;

                if (currentClient.isAutorized == false)
                {
                    if (msgReceived.cmdCommand == Command.Login)
                    {
                        msgReceived.strMessage = msgReceived.strMessage == null ? "" : msgReceived.strMessage;
                        if (msgReceived.strMessage == _password)
                        {

                            currentClient.isAutorized = true;
                            currentClient.isAlive = true;
                            currentClient.strName = msgReceived.strName;
                            currentClient.clr = msgReceived.clientColor;

                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room, Color is " + msgReceived.clientColor.ToString() + ">>>";
                            msgToSend.clientColor = msgReceived.clientColor;

                            //txtLog.Text += msgToSend.strMessage + "\r\n";

                            SendToAll(msgToSend.ToByte(), currentClient.socket);
                        }
                        else
                        {
                            msgToSend.cmdCommand = Command.LoginError;
                            foreach (ClientInfo client in clientList)
                            {
                                if (client.socket == currentClientSocket)
                                {
                                    clientList.Remove(client);
                                    break;
                                }
                            }

                            //txtLog.Text += "Client" + msgToSend.strName + "have sent a wrong password!\r\n";
                        }

                        message = msgToSend.ToByte();

                        //Send the name of the users in the chat room
                        currentClientSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                new AsyncCallback(OnSend), currentClientSocket);

                    }
                }

                if (currentClient.isAutorized == true)
                {
                    switch (msgReceived.cmdCommand)
                    {
                        case Command.Logout:
                            RemoveClient(currentClientSocket);
                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the room>>>";

                            SendToAll(msgToSend.ToByte());
                            break;

                        case Command.Message:
                            msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                            SendToAll(msgToSend.ToByte());
                            break;

                        case Command.PositionNew:
                            currentClient.oldPnt = msgReceived.pnt1;
                            break;

                        case Command.PositionNext:
                            msgReceived.pnt1 = currentClient.oldPnt;
                            msgToSend = msgReceived;
                            SendToAll(msgToSend.ToByte());
                            currentClient.oldPnt = msgReceived.pnt2;
                            break;

                        case Command.BitmapInfoRequest:
                            if (clientList.Count > 1) {
                                Data msgBitmap = new Data();
                                msgBitmap.strName = (clientList.Count - 1).ToString();
                                msgBitmap.cmdCommand = Command.BitmapInfoRequest;
                                message = msgBitmap.ToByte();

                                ClientInfo clTmp = (ClientInfo)clientList[0];
                                clTmp.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                    new AsyncCallback(OnSend), clTmp.socket);
                            }
                            break;

                        case Command.BitmapInfoResult:
                            if (msgReceived.strMessage[0] == 'L')
                                currentClient.byteData = new byte[System.Convert.ToInt32(msgReceived.strMessage.Split(' ')[1]) + 50];
                            message = msgReceived.ToByte();
                            ClientInfo clBmp = (ClientInfo)clientList[System.Convert.ToInt32(msgReceived.strName)];
                            clBmp.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                    new AsyncCallback(OnSend), clBmp.socket);
                            break;

                        case Command.ClientList:

                            //Send the names of all users in the chat room to the new user
                            msgToSend.cmdCommand = Command.ClientList;
                            msgToSend.strName = null;
                            msgToSend.strMessage = null;

                            //Collect the names of the user in the chat room
                            foreach (ClientInfo client in clientList) {
                                //To keep things simple we use asterisk as the marker to separate the user names
                                msgToSend.strMessage += client.strName + "*";
                            }

                            message = msgToSend.ToByte();

                            //Send the name of the users in the chat room
                            currentClientSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                    new AsyncCallback(OnSend), currentClientSocket);
                            break;

                        case Command.TestPackageRecieve:
                            mut.WaitOne();

                            _testResult += int.Parse(msgReceived.strMessage);// / (float)_testNum;
                            _flagTest++;
                            GetResult();

                            mut.ReleaseMutex();
                            break;
                    }
                }

                String _msg = msgReceived.strMessage == null ? "Empty" : msgReceived.strMessage;
                //txtLog.Text += "Client: " + msgReceived.strName + ", Command: " + msgReceived.cmdCommand.ToString() +  ", Message: " + _msg + "\r\n";
                //If the user is logging out then we need not listen from her
                if (msgReceived.cmdCommand != Command.Logout && msgToSend.cmdCommand != Command.LoginError)
                {
                    //Start listening to the message send by the user
                    currentClientSocket.BeginReceive(currentClient.byteData, 0, currentClient.byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), currentClientSocket);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSserverTCP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 5
0
        private void OnReceiveRegistrate(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint epSender = (EndPoint)ipeSender;

                _publicSocket.EndReceive(ar, ref ipeSender);

                //We will send this object in response the users request
                Data msgToSend = new Data();

                byte[] message;

                        //Send the names of all users in the chat room to the new user
                msgToSend.cmdCommand = Command.ServerList;
                msgToSend.strName = _serverName;
                msgToSend.strMessage = IPHost.ToString();

                message = msgToSend.ToByte();

                //Send the IP of server
                _publicSocket.BeginSend(message, message.Length, ipeSender, new AsyncCallback(OnSendRegistrate), _publicSocket);

                //Print Log on server about requests!
                //txtLog.Text += "Server have sent the info to new client! \r\n";

                //Start listening to the message send by the user
                _publicSocket.BeginReceive(new AsyncCallback(OnReceiveRegistrate), ipeSender);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 6
0
        private void OnReceive(IAsyncResult ar)
        {
            #region Local variables / converting received message
            try
            {
                Socket clientSocket = (Socket)ar.AsyncState;
                clientSocket.EndReceive(ar);
                //Transform the array of bytes received from the user into an
                //intelligent form of object Data
                Data msgReceived = new Data(byteData);
                //We will send this object in response the users request
                Data msgToSend = new Data();
                byte[] message;
                //If the message is to login, logout, or simple text message
                //then when send to others the type of the message remains the same
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName = msgReceived.strName;
            #endregion
               
                
                    #region Command.NewGame
                
                if (msgReceived.cmdCommand == Command.NewGame)
                {
                    newGameCount = 0;
                    NewGame();
                    msgToSend.cmdCommand = Command.NewGame;
                    message = msgToSend.ToByte();
                            foreach (ClientInfo clientInfo in clientList)
                            {
                                if (clientInfo.socket != clientSocket ||
                                    msgToSend.cmdCommand != Command.Login)
                                {
                                    //Send the message to all users
                                    clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                        new AsyncCallback(OnSend), clientInfo.socket);
                                }
                            }
                            RaiseEvent("Both players have agreed to start a new game. \r\n");
                }
                    #endregion
                else
                {
                #region Make Move Command              
                if (msgReceived.cmdCommand == Command.MakeMove)//MAKE A METHOD HERE TO CHECK AN ARRAY LIST FOR VALID MOVES
                //IF IT IS A VALID MOVE THEN MAKE CHANGES TO ARRAY TO REFLECT THE MOVE THAT WAS MADE
                {
                   RaiseEvent("strMessage: " + msgReceived.strMessage + Environment.NewLine + "cmdCommand: " + msgReceived.cmdCommand.ToString() + Environment.NewLine + "strName: " + msgReceived.strName.ToString() + Environment.NewLine);               
                    msgReceived.cmdCommand = Command.Message;
                    if (CheckValidity(ColumnCheck(Convert.ToInt32(msgReceived.strMessage))))
                    {//if true, means that there is still space in the column to put a chip
                        int currentrow = RowCorrect(ColumnCheck(Convert.ToInt32(msgReceived.strMessage)));
                        int currentcolumn = Convert.ToInt32(msgReceived.strMessage) - 1;
                        MoveToSend = turn.ToString() + "," + currentcolumn + "," + currentrow;
                        if (turn == PlayerTurn.Black)
                        {
                            zonelist[currentcolumn, currentrow] = ChipColor.Black;
                            turn = PlayerTurn.Red;
                        }
                        else
                        {
                            zonelist[currentcolumn, currentrow] = ChipColor.Red;
                            turn = PlayerTurn.Black;
                        }                       
                        msgReceived.cmdCommand = Command.SendMove;
                        RowIncrease(currentcolumn);
                        if (CheckWin())
                        {
                            msgToSend.cmdCommand = Command.Win;
                            msgToSend.strMessage = MoveToSend + "," + winningCombination;
                            //make the last move of the game and announce the current player is the winner
                        }
                        else
                        {
                            if (turn == PlayerTurn.Black)
                                turn = PlayerTurn.Red;
                            else
                                turn = PlayerTurn.Black;
                            //make a command here to change the player's boards and also change current turn
                        }     
                        if (turn == PlayerTurn.Black)
                            turn = PlayerTurn.Red;
                        else
                            turn = PlayerTurn.Black;
                    }
                    else//need to add a command in here to return an invalid move message to the player
                    {
                        ValidorInvalidMove = false;
                        msgToSend.cmdCommand = Command.Message;
                        msgToSend.strMessage = "The column you selected is not a valid move. Try again.";
                    }
                }
                #endregion
                if (ValidorInvalidMove)//only relevant if player did not make a move or made a valid move
                {
                    if (msgToSend.cmdCommand != Command.Win)
                    {
                        switch (msgReceived.cmdCommand)
                        {
                            #region Login Command
                            case Command.Login:
                                //When a user logs in to the server then we add her to our
                                //list of clients
                                ClientInfo clientInfo = new ClientInfo();
                                clientInfo.socket = clientSocket;
                                clientInfo.strName = msgReceived.strName;
                                Random rnd = new Random();
                                if (clientList.Count == 0)
                                {
                                    if (rnd.Next(0, 2) == 0)
                                    {
                                        clientInfo.strName = "Black";
                                        playerBlackSocket = clientSocket;
                                    }
                                    else
                                    {
                                        clientInfo.strName = "Red";
                                        playerRedSocket = clientSocket;
                                    }
                                    colorDif = clientInfo.strName;
                                }
                                else if (clientList.Count == 1)
                                {
                                    if (colorDif == "Black")
                                    {
                                        clientInfo.strName = "Red";
                                        playerRedSocket = clientSocket;
                                    }
                                    else
                                    {
                                        clientInfo.strName = "Black";
                                        playerBlackSocket = clientSocket;
                                    }
                                    msgToSend.cmdCommand = Command.BeginGame;
                                    msgToSend.strMessage = "first";
                                    message = msgToSend.ToByte();
                                    playerBlackSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                            new AsyncCallback(OnSend), playerBlackSocket);
                                    msgToSend.strMessage = "second";
                                    message = msgToSend.ToByte();
                                    playerRedSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                            new AsyncCallback(OnSend), playerRedSocket);

                                    
                                msgToSend.cmdCommand = Command.List;
                                msgToSend.strName = null;
                                msgToSend.strMessage = null;
                                //Collect the names of the user in the chat room
                                foreach (ClientInfo client in clientList)
                                {
                                    //To keep things simple we use asterisk as the marker to separate the user names
                                    msgToSend.strMessage += client.strName + "*";
                                    message = msgToSend.ToByte();
                                }
                                    
                                }
                                else if(clientList.Count ==2)
                                {
                                    clientSocket.Disconnect(false);
                                    break;
                                }
                                if (clientList.Count <= 2)
                                {
                                    msgReceived.strName = clientInfo.strName;
                                    clientList.Add(clientInfo);
                                    //Set the text of the message that we will broadcast to all users
                                    msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                                }
                                break;
                            #endregion
                            #region Logout Command
                            case Command.Logout:
                                //When a user wants to log out of the server then we search for her 
                                //in the list of clients and close the corresponding connection
                                int nIndex = 0;
                                foreach (ClientInfo client in clientList)
                                {
                                    if (client.socket == clientSocket)
                                    {
                                        clientList.RemoveAt(nIndex);
                                        break;
                                    }
                                    ++nIndex;
                                }
                                clientSocket.Close();
                                msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the room>>>";
                                break;
                            #endregion
                            #region Message Command
                            case Command.Message:
                                //Set the text of the message that we will broadcast to all users
                                msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                                break;
                            #endregion
                            #region Win Command
                            case Command.Win:
                                msgToSend.cmdCommand = Command.SendMove;
                                msgToSend.strMessage = MoveToSend + "," + winningCombination;
                                message = msgToSend.ToByte();
                                foreach (ClientInfo client in clientList)
                                {
                                 
                                        if (client.socket != clientSocket ||
                                        msgToSend.cmdCommand != Command.Login)
                                    {
                                        //Send the message to all users
                                        client.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                            new AsyncCallback(OnSend), client.socket);
                                    }
                                }
                                break;
                            #endregion
                            #region Send Moves
                            case Command.SendMove:
                                msgToSend.cmdCommand = Command.SendMove;
                                msgToSend.strMessage = MoveToSend;
                                message = msgToSend.ToByte();
                                foreach (ClientInfo client in clientList)
                                {
                                    if (client.socket != clientSocket ||
                                        msgToSend.cmdCommand != Command.Login)
                                    {
                                        //Send the message to all users
                                        client.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                            new AsyncCallback(OnSend), client.socket);
                                    }
                                }
                                break;
                            #endregion
                            #region List Command
                            case Command.List:
                                //Send the names of all users in the chat room to the new user
                                msgToSend.cmdCommand = Command.List;
                                msgToSend.strName = null;
                                msgToSend.strMessage = null;
                                //Collect the names of the user in the chat room
                                foreach (ClientInfo client in clientList)
                                {
                                    //To keep things simple we use asterisk as the marker to separate the user names
                                    msgToSend.strMessage += client.strName + "*";
                                    message = msgToSend.ToByte();
                                    //Send the name of the users in the chat room
                                    
                                    //clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                          //  new AsyncCallback(OnSend), clientSocket);
                                }
                                foreach (ClientInfo client in clientList)
                                {
                                    message = msgToSend.ToByte();
                                    client.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                                new AsyncCallback(OnSend), client.socket);

                                }

                                break;
                            #endregion
                        }
                        #region Send message to all clients
                        if (msgToSend.cmdCommand != Command.List && msgToSend.cmdCommand != Command.SendMove && msgToSend.cmdCommand != Command.BeginGame)   //List messages are not broadcasted
                        {
                            message = msgToSend.ToByte();
                            foreach (ClientInfo clientInfo in clientList)
                            {
                                if (clientInfo.socket != clientSocket ||
                                    msgToSend.cmdCommand != Command.Login)
                                {
                                    //Send the message to all users
                                    clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                        new AsyncCallback(OnSend), clientInfo.socket);
                                }
                            }
                            RaiseEvent(msgToSend.strMessage + "\r\n");
                        }
                        #endregion
                    } 
                }
                #region Win / Game Over
                if (msgToSend.cmdCommand == Command.Win)
                {
                    message = msgToSend.ToByte();
                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.socket != clientSocket ||
                            msgToSend.cmdCommand != Command.Login)
                        {
                            //Send the message to all users
                            clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                new AsyncCallback(OnSend), clientInfo.socket);
                        }
                    }
                    RaiseEvent(msgToSend.strMessage + "\r\n");
                }
                #endregion
                #region Made an Invalid Move
                if(!ValidorInvalidMove)
                {
                    ValidorInvalidMove = true;
                    message = msgToSend.ToByte();
                    clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                    new AsyncCallback(OnSend), clientSocket);
                    RaiseEvent(msgReceived.strName + " just made an invalid move! \r\n");
                }
                #endregion
                #region Begin Receive, Happens every time on receive
                //If the user is logging out then we need not listen from her
            }
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    //Start listening to the message send by the user
                    clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
                }
            }
            catch (Exception ex)
            {
                RaiseEvent(ex.Message);
            }
        }
Exemplo n.º 7
0
 public void Load(Client client, Data receive, List<Client> clientList = null, List<Channel> channelsList = null)
 {
     Received = receive;
     Client = client;
     ListOfClientsOnline = clientList;
 }
        /// <summary>
        /// Setup a player action, by going through the received data and figuring out which action
        /// a player is performing (move, shoot, etc.)
        /// </summary>
        /// <param name="msgReceived">Received data</param>
        /// <returns>Data object of player action</returns>
        private Data PlayerAction(Data msgReceived)
        {
            //Required variables
            Player playermoved = null;
            double accelerate = 0;
            int rot = 0;

            //Figure out who is making the action.
            foreach (Player playerp in playerList)
            {
                if (playerp.id == msgReceived.id)
                {
                    playermoved = playerp;
                }

            }
            //Setup our new message to send.
            Data msgToSend = new Data();
            //Rotate right
            if (msgReceived.strMessage == "right")
            {
                rot++;
                rot = rot * MatchConfig.rotationRate;
                playermoved.angle += rot;

            }
            //Rotate left
            if (msgReceived.strMessage == "left")
            {
                rot++;
                rot = rot * MatchConfig.rotationRate;
                playermoved.angle -= rot;

            }
            //Increase speed
            if (msgReceived.strMessage == "up")
            {

                // this is to highlight that the Math.Sin and Math.Cos use the radian
                // for its "angle" It also demenstrates that we need to store our
                // locations using floats as it will allow for nice turning rather
                // than fixed 8-directional (N, NE, E, SE, S, SW, W, NW) movement
                accelerate++;
                accelerate = accelerate * MatchConfig.accelerationRate;
                float rad = (float)(Math.PI / 180) * playermoved.angle;
                playermoved.speedX += (float)((float)Math.Sin(rad) * accelerate);
                playermoved.speedY += -1 * (float)((float)Math.Cos(rad) * accelerate);
                //Note we don't actually increase the x or y here, just the speed.
            }
            //Decrease speed
            if (msgReceived.strMessage == "down")
            {
                accelerate++;
                accelerate = accelerate * MatchConfig.brakeRate;
                float rad = (float)(Math.PI / 180) * playermoved.angle;
                playermoved.speedX -= (float)((float)Math.Sin(rad) * accelerate);
                playermoved.speedY -= -1 * (float)((float)Math.Cos(rad) * accelerate);
                //Note we don't actually decrease the x or y here, just the speed.

            }
            //Shoot command
            if (msgReceived.strMessage == "shoot")
            {
                //Check that the player has less than 10 bullets onscreen.
                if (playermoved.bcount < 10)
                {
                    playermoved.bcount++;
                    Bullet bullet = new Bullet();
                    bullet.speedX= playermoved.speedX;
                    //Setup bullet's speeds
                    if (playermoved.speedX >= 0)
                    {
                        bullet.speedX= (float)(playermoved.speedX + Math.Sin((Math.PI / 180) * playermoved.angle) * MatchConfig.bulletSpeed);
                    }
                    else
                    {
                        bullet.speedX= (float)(playermoved.speedX + Math.Sin((Math.PI / 180) * playermoved.angle) * MatchConfig.bulletSpeed);
                    }
                    if (playermoved.speedY >= 0)
                    {
                        bullet.speedY= ((float)(playermoved.speedY + (-1 * (Math.Cos((Math.PI / 180) * playermoved.angle))) * MatchConfig.bulletSpeed));
                    }
                    else
                    {
                        bullet.speedY= ((float)(playermoved.speedY + (-1 * (Math.Cos((Math.PI / 180) * playermoved.angle))) * MatchConfig.bulletSpeed));
                    }
                    //Setup bullet location
                    bullet.x = (float)(playermoved.x + Math.Sin((Math.PI / 180) * playermoved.angle) * (playermoved.radius + 10));
                    bullet.y = (float)(playermoved.y + (-1 * (Math.Cos((Math.PI / 180) * playermoved.angle))) * (playermoved.radius + 10));
                    //Add who shot the bullet
                    bullet.whoshot = playermoved.id;
                    //Increase the overall bullet count (used for ids)
                    bulletcount++;
                    bullet.id = bulletcount;
                    //Add the bullet to the list
                    bulletList.Add(bullet);
                }

            }//End shoot command
            //Return the player action
            return msgToSend;
        }
        /// <summary>
        /// This is the update loop used to constantly update the game objects
        /// checking for collisions, and removing objects
        /// </summary>
        public void Update()
        {
            //Required variables
            byte[] message;
            Player playerbullet = null;
            List<Bullet> toRemove = new List<Bullet>();
            Data msgToSend = new Data();
            //Loop forever
            while (true)
            {
                //Wait 40 ms
                Thread.Sleep(40);

                //Update planets
                foreach (Planets planet in planetList)
                {
                    planet.x = 400;
                    planet.y = 300;
                }
                //Update players
                foreach (Player p in playerList)
                {
                    //Adjust placement by speed
                    p.x += p.speedX;
                    p.y += p.speedY;

                    //Collision Detection between Player and Border. For now, Players will bounce off the border in opposite direction.
                    if (p.x < 0)
                    {
                        p.speedX = p.speedX * (float)(-0.1);
                        p.x = 0;
                    }
                    else if (p.x > MatchConfig.mapWidth)
                    {
                        p.speedX = p.speedX * (float)(-0.1);
                        p.x = MatchConfig.mapWidth;
                    }
                    if (p.y < 0)
                    {
                        p.speedY = p.speedY * (float)(-0.1);
                        p.y = 0;
                    }
                    else if (p.y > MatchConfig.mapHeight)
                    {
                        p.speedY = p.speedY * (float)(-0.1);
                        p.y = MatchConfig.mapHeight;
                    }

                    //Collision Detection between Players. For now, Players will bounce off of each other. No damage to players.
                    foreach (Player p2 in playerList)
                    {
                        if (p.checkCollision(p2))
                        {
                            p.treatCollision(p2);
                        }
                    }

                    //Gravity and Collision Detection between Planet and players
                    foreach (Planets planet in planetList)
                    {
                        planet.applyGravity(p);

                        //Collision Detection between player and planets. For now, Players will bounce off of the planet. No damage to each other.
                        if (p.checkCollision(planet))
                        {
                            p.treatCollision(planet);
                        }
                    }
                }//end of player loop

                //Update bullets
                foreach (Bullet b in bulletList)
                {
                    //Check who shot each bullet, (required for the max bullet count per player)
                    foreach (Player playerp in playerList)
                    {
                        if (playerp.id == b.whoshot)
                        {
                            playerbullet = playerp;
                        }
                    }

                    //Bullet Movement
                    b.x += b.speedX;
                    b.y += b.speedY;

                    //Collision Detection between bullets and border. At this time, bullets will disappear after they reach the border.
                    if (b.x < 0)
                    {
                        playerbullet.bcount--;
                        toRemove.Add(b);
                    }
                    else if (b.x > MatchConfig.mapWidth)
                    {
                        playerbullet.bcount--;
                        toRemove.Add(b);
                    }
                    if (b.y < 0)
                    {
                        playerbullet.bcount--;
                        toRemove.Add(b);
                    }
                    else if (b.y > MatchConfig.mapHeight)
                    {
                        playerbullet.bcount--;
                        toRemove.Add(b);
                    }

                    //Collision Detection between players and bullets. For now, the bullets will disappear when they collide with players. Players will remain.
                    foreach (Player p in playerList)
                    {
                        if (b.checkCollision(p))
                        {
                            //remove bullet
                            playerbullet.bcount--;
                            toRemove.Add(b);
                            //remove player
                            //TODO: Add code/lists to delete players when collide with bullets
                        }
                    }

                    //Collision Detection and Gravity between planet and bullets.
                    foreach (Planets planet in planetList)
                    {
                        //Collision Detection between planet and bullets. For now, the bullets will disappear when they collide with the planet.
                        if (b.checkCollision(planet))
                        {
                            playerbullet.bcount--;
                            toRemove.Add(b);
                        }

                        planet.applyGravity(b);
                    }
                }//End bullet loop

                //Remove bullets
                foreach (Bullet r in toRemove)
                {
                    //Add to the list of bullet ids to remove
                    removeids.Add(r.id);
                    bulletList.Remove(r);
                }

                //Create the message to send to the clients
                message = msgToSend.ToByte(playerList, bulletList, removeids, playercount, planetList);

                //Loop through all clients
                foreach (ClientInfo clientInfo in clientList)
                {
                    //Send the message to all users
                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint, new AsyncCallback(OnSend), clientInfo.endpoint);
                }
            }//End while loop
        }
Exemplo n.º 10
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                Socket clientSocket = (Socket)ar.AsyncState;
                clientSocket.EndReceive(ar);

                //Transform the array of bytes received from the user into an
                //intelligent form of object Data
                Data msgReceived = new Data(byteData);

                //We will send this object in response the users request
                Data msgToSend = new Data();

                byte [] message;

                //If the message is to login, logout, or simple text message
                //then when send to others the type of the message remains the same
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName    = msgReceived.strName;

                switch (msgReceived.cmdCommand)
                {
                case Command.Login:

                    //When a user logs in to the server then we add her to our
                    //list of clients

                    ClientInfo clientInfo = new ClientInfo();
                    clientInfo.socket  = clientSocket;
                    clientInfo.strName = msgReceived.strName;

                    clientList.Add(clientInfo);

                    //Set the text of the message that we will broadcast to all users
                    msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                    break;

                case Command.Logout:

                    //When a user wants to log out of the server then we search for her
                    //in the list of clients and close the corresponding connection

                    int nIndex = 0;
                    foreach (ClientInfo client in clientList)
                    {
                        if (client.socket == clientSocket)
                        {
                            clientList.RemoveAt(nIndex);
                            break;
                        }
                        ++nIndex;
                    }

                    clientSocket.Close();

                    msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the room>>>";
                    break;

                case Command.Message:

                    //Set the text of the message that we will broadcast to all users
                    msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                    break;

                case Command.List:

                    //Send the names of all users in the chat room to the new user
                    msgToSend.cmdCommand = Command.List;
                    msgToSend.strName    = null;
                    msgToSend.strMessage = null;

                    //Collect the names of the user in the chat room
                    foreach (ClientInfo client in clientList)
                    {
                        //To keep things simple we use asterisk as the marker to separate the user names
                        msgToSend.strMessage += client.strName + "*";
                    }

                    message = msgToSend.ToByte();

                    //Send the name of the users in the chat room
                    clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                           new AsyncCallback(OnSend), clientSocket);
                    break;
                }

                if (msgToSend.cmdCommand != Command.List)   //List messages are not broadcasted
                {
                    message = msgToSend.ToByte();

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.socket != clientSocket ||
                            msgToSend.cmdCommand != Command.Login)
                        {
                            //Send the message to all users
                            clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                                        new AsyncCallback(OnSend), clientInfo.socket);
                        }
                    }

                    WriteMessage(msgToSend);
                }

                //If the user is logging out then we need not listen from her
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    //Start listening to the message send by the user
                    clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSserverTCP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// This function is to unpack all the data received from a client.
        /// </summary>
        /// <param name="ar">Status of the asynchronous operation</param>
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                //Required variables
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint epSender = (EndPoint)ipeSender;
                serverSocket.EndReceiveFrom(ar, ref epSender);
                byte[] message;
                //Transform the array of bytes received from the user into an
                //intelligent form of object Data
                Data msgReceived = new Data(byteData);

                //We will send this object in response the users request
                Data msgToSend = new Data();

                //If the message is to login, logout, or simple text message
                //then when send to others the type of the message remains the same
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName = msgReceived.strName;

                //Check which kind of message we received
                switch (msgReceived.cmdCommand)
                {
                    case Command.Login:
                        //When a user logs in to the server then we add her to our
                        //list of clients
                        if (playercount == 0)
                        {
                            //Setup player 1
                            Player player1 = new Player();
                            ClientInfo clientInfo = new ClientInfo();
                            clientInfo.endpoint = epSender;
                            clientInfo.strName = msgReceived.strName;
                            msgToSend.cmdCommand = Command.Login;
                            msgToSend.id = playercount;
                            clientList.Add(clientInfo);
                            player1.x = 100;
                            player1.y = 100;
                            player1.radius = 16;
                            player1.playername = msgReceived.strName;
                            player1.id = playercount;
                            playerList.Add(player1);
                            playercount = playercount + 1;

                            //Setup planets (1 for now)
                            Planets planet = new Planets();
                            planet.x = 400;
                            planet.y = 300;
                            planet.radius = 32;
                            planet.mass = 150;
                            planetList.Add(planet);
                            planetcount = 1;

                            //Set the text of the message that we will broadcast to all users (doesn't currently do much)
                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                            msgToSend.cmdCommand = Command.Login;

                        }
                        else
                        {
                            //Setup player 2
                            Player player2 = new Player();
                            ClientInfo clientInfo = new ClientInfo();
                            clientInfo.endpoint = epSender;
                            clientInfo.strName = msgReceived.strName;
                            msgToSend.id = playercount;
                            player2.id = playercount;
                            clientList.Add(clientInfo);
                            player2.x = 700;
                            player2.y = 500;
                            player2.radius = 16;
                            player2.playername = msgReceived.strName;
                            player2.id = playercount;
                            playerList.Add(player2);
                            playercount = playercount + 1;

                            //Set the text of the message that we will broadcast to all users
                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                            msgToSend.cmdCommand = Command.Login;
                        }
                        break; //End case login

                    case Command.Create:
                        //Create objects (not currently in use)
                        break; //End case create

                    case Command.Logout:
                        //When a user wants to log out of the server then we search for her
                        //in the list of clients and close the corresponding connection
                        //TODO: Fix logout errors.
                        int nIndex = 0;
                        foreach (ClientInfo client in clientList)
                        {
                            if (client.endpoint == epSender)
                            {
                                clientList.RemoveAt(nIndex);
                                break;
                            }
                            ++nIndex;
                        }
                        //Set the text of the message that we will broadcast to all users
                        msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the room>>>";
                        break; //End case logout

                    case Command.Message:
                        //Set the text of the message that we will broadcast to all users
                        msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                        break;//End case message

                    case Command.Move:
                        //Setup the move command
                        msgToSend = PlayerAction(msgReceived);
                        msgToSend.cmdCommand = msgReceived.cmdCommand;
                        break;//End case move

                    case Command.List:
                        //Send the names of all users in the chat room to the new user
                        msgToSend.cmdCommand = Command.List;
                        msgToSend.strName = null;
                        msgToSend.strMessage = null;

                        //Collect the names of the user in the chat room
                        foreach (ClientInfo client in clientList)
                        {
                            //To keep things simple we use asterisk as the marker to separate the user names
                            msgToSend.strMessage += client.strName + "*";
                        }
                        //Setup our message to send
                        message = msgToSend.ToByte(playerList, bulletList, removeids, playercount, planetList);

                        //Send the name of the users in the chat room
                        serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender, new AsyncCallback(OnSend), epSender);
                        break;
                }//End command list

                //TODO: Add check to see if it is a login, if it is send the players ID to the client
                //When the client receives the login response it will set the users ID to the correct value
                if (msgToSend.cmdCommand == Command.Login)
                {
                    //Send the login message
                    message = msgToSend.ToByte(playerList, bulletList, removeids, playercount, planetList);
                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender, new AsyncCallback(OnSend), epSender);
                    msgToSend.cmdCommand = Command.Create;
                    message = msgToSend.ToByte(playerList, bulletList, removeids, playercount, planetList);
                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender, new AsyncCallback(OnSend), epSender);
                    msgToSend.cmdCommand = Command.Login;
                }

                if (msgToSend.cmdCommand != Command.List)
                {
                    //Setup the list message
                    message = msgToSend.ToByte(playerList, bulletList, removeids, playercount, planetList);

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        //Send the message to all users
                        serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                            new AsyncCallback(OnSend), clientInfo.endpoint);
                    }
                }

                //If the user is logging out then we need not listen from her
                //Start listening to the message send by the user
                serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);

            }
            //Exception handling
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "GameUDPServer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 12
0
        private void parseMessage(Socket clientSocket)
        {
            try
            {
                if (isClosing != true)
                {
                    //Transform the array of bytes received from the user into an
                    //intelligent form of object Data
                    Data msgReceived = new Data(byteData);

                    //We will send this object in response the users request
                    Data msgToSend = new Data();

                    byte[] message;

                    bool isBanned = false;
                    if (File.Exists("base/banlist.ini"))
                    {
                        using (StreamReader r = new StreamReader("base/banlist.ini"))
                        {
                            while (!r.EndOfStream)
                            {
                                if (r.ReadLine().StartsWith(clientSocket.RemoteEndPoint.ToString().Split(':')[0]))
                                {
                                    isBanned = true;
                                    break;
                                }
                            }
                        }
                    }

                    //If the message is to login, logout, or simple text message
                    //then when sent to others, the type of the message remains the same
                    msgToSend.cmdCommand = msgReceived.cmdCommand;
                    msgToSend.strName = msgReceived.strName;

                    switch (msgReceived.cmdCommand)
                    {
                        case Command.Login:
                            //When a user logs in to the server then we add her to our
                            //list of clients

                            if (msgReceived.strName == null || msgReceived.strName == "")
                            {
                                appendTxtLogSafe("<<" + clientSocket.RemoteEndPoint.ToString() + " send an invalid Login packet>>\r\n");
                                clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
                                return;
                            }

                            ClientInfo clientInfo = new ClientInfo();
                            clientInfo.socket = clientSocket;
                            clientInfo.strName = msgReceived.strName;
                            clientList.Add(clientInfo);
                            appendLstUsersSafe(msgReceived.strName + " - " + ((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString());

                            //Set the text of the message that we will broadcast to all users
                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has entered the courtroom>>>";
                            userNumStat.Text = "Users Online: " + clientList.Count;

                            /* //DO THE SAME STUFF AS IF THE CLIENT SENT A LIST COMMAND
                            //Send the names of all users in the chat room to the new user
                            msgToSend.cmdCommand = Command.List;
                            msgToSend.strName = null;
                            msgToSend.strMessage = null;

                            //Collect the names of the user in the chat room
                            foreach (ClientInfo client in clientList)
                            {
                                //To keep things simple we use asterisk as the marker to separate the user names
                                msgToSend.strMessage += client.strName + "*";
                            } */

                            message = msgToSend.ToByte();

                            //Send the name of the users in the chat room
                            //clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(OnSend), clientSocket);
                            break;

                        case Command.Logout:
                            //When a user wants to log out of the server then we search for her
                            //in the list of clients and close the corresponding connection

                            int nIndex = 0;
                            foreach (ClientInfo client in clientList)
                            {
                                if (client.socket == clientSocket)
                                {
                                    clientList.RemoveAt(nIndex);
                                    //removeLstUsersSafe(client.strName + " - " + client.character);
                                    removeLstUsersSafe(client.strName + " - " + ((IPEndPoint)client.socket.RemoteEndPoint).Address.ToString());
                                    break;
                                }
                                ++nIndex;
                            }

                            clientSocket.Close();

                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the courtroom>>>";
                            userNumStat.Text = "Users Online: " + clientList.Count;
                            break;

                        case Command.ChangeMusic:
                            if (msgReceived.strMessage != null & msgReceived.strName != null)
                            {
                                msgToSend.cmdCommand = Command.ChangeMusic;
                                msgToSend = msgReceived;
                                appendTxtLogSafe("<<<" + msgReceived.strName + " changed the music to " + msgReceived.strMessage + ">>>\r\n");
                            }
                            break;

                        case Command.ChangeHealth:
                            if (msgReceived.strMessage != null & msgReceived.strName != null)
                            {
                                msgToSend = msgReceived;
                            }
                            break;

                        case Command.Message:
                        case Command.Present:
                            //Set the text of the message that we will broadcast to all users
                            msgToSend = msgReceived;
                            msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                            break;

                        case Command.List:
                            //Send the names of all users in the chat room to the new user
                            msgToSend.cmdCommand = Command.List;
                            msgToSend.strName = null;
                            msgToSend.strMessage = null;

                            //Collect the names of the user in the chat room
                            foreach (ClientInfo client in clientList)
                            {
                                //To keep things simple we use asterisk as the marker to separate the user names
                                msgToSend.strMessage += client.strName + "*";
                            }

                            message = msgToSend.ToByte();

                            //Send the name of the users in the chat room
                            clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(OnSend), clientSocket);
                            break;

                        case Command.PacketSize:
                            //First, send all of the current case's evidence data
                            sendEvidence(clientSocket);

                            msgToSend.cmdCommand = Command.DataInfo;
                            msgToSend.strName = null;
                            msgToSend.strMessage = "";

                            List<string> allChars = iniParser.GetCharList();
                            List<string> charsInUse = new List<string>();
                            foreach (string cName in allChars)
                            {
                                if (clientList != null && clientList.Count > 0)
                                {
                                    foreach (ClientInfo client in clientList)
                                    {
                                        if (client.strName == cName)
                                        {
                                            charsInUse.Add(cName);
                                        }
                                    }
                                }
                            }

                            foreach (string cName in charsInUse)
                            {
                                allChars.Remove(cName);
                            }

                            msgToSend.strMessage += allChars.Count + "|";
                            foreach (string cName in allChars)
                            {
                                msgToSend.strMessage += cName + "|";
                            }

                            List<string> songs = iniParser.GetMusicList();
                            msgToSend.strMessage += songs.Count + "|";
                            foreach (string song in songs)
                            {
                                msgToSend.strMessage += song + "|";
                            }

                            message = msgToSend.ToByte(true);
                            //byte[] evidence = iniParser.GetEvidenceData().ToArray();
                            //if (evidence.Length > 0)
                            //    allData = message.Concat(evidence).ToArray();
                            //else
                            allData = message;

                            Data sizeMsg = new Data();
                            if (!isBanned)
                            {
                                sizeMsg.cmdCommand = Command.PacketSize;
                                sizeMsg.strMessage = allData.Length.ToString();
                            }
                            else
                            {
                                sizeMsg.cmdCommand = Command.Disconnect;
                            }

                            byte[] sizePacket = sizeMsg.ToByte();
                            clientSocket.BeginSend(sizePacket, 0, sizePacket.Length, SocketFlags.None, new AsyncCallback(OnSend), clientSocket);
                            break;

                        case Command.DataInfo:
                            if (!isBanned)
                                clientSocket.BeginSend(allData, 0, allData.Length, SocketFlags.None, new AsyncCallback(OnSend), clientSocket);
                            break;
                    }

                    if (msgToSend.cmdCommand != Command.List & msgToSend.cmdCommand != Command.DataInfo & msgToSend.cmdCommand != Command.PacketSize)   //List messages are not broadcasted
                    {
                        message = msgToSend.ToByte(); // TO DO: REMOVE THE OTHER CALLS TO THIS IN THE INDIVIDUAL SWITCH CASES, THEY ARE PROBABLY REDUNDANT

                        foreach (ClientInfo clientInfo in clientList)
                        {
                            //if the command is login, dont send the login notification to the person who's logging in, its redundant
                            if (clientInfo.socket != clientSocket || msgToSend.cmdCommand != Command.Login)
                            {
                                //Send the message to all users
                                clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(OnSend), clientInfo.socket);
                            }
                        }
                        if (msgToSend.cmdCommand != Command.ChangeMusic & msgToSend.cmdCommand != Command.ChangeHealth)
                            if (msgReceived.callout <= 3)
                                appendTxtLogSafe(msgToSend.strMessage.Split('|')[0] + "\r\n");
                    }

                    //If the user is logging out then we need not listen from her
                    if (msgReceived.cmdCommand != Command.Logout)
                    {
                        //Start listening to the messages sent by the user
                        clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
                    }
                }
            }
            catch (ObjectDisposedException)
            { }
            catch (SocketException)
            { }
            catch (Exception ex)
            {
                if (Program.debug)
                    MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace.ToString(), "AODXServer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 13
0
        private void kickUser(bool silent = false)
        {
            if (lstUsers.SelectedItem != null)
            {
                string username = ((string)lstUsers.SelectedItem).Split(new string[] { " - " }, StringSplitOptions.None)[0];
                int nIndex = 0;
                foreach (ClientInfo client in clientList)
                {
                    if (client.strName == username)
                    {
                        clientList.RemoveAt(nIndex);
                        //removeLstUsersSafe(client.strName + " - " + client.character);
                        removeLstUsersSafe(client.strName + " - " + ((IPEndPoint)client.socket.RemoteEndPoint).Address.ToString());
                        client.socket.Close();
                        break;
                    }
                    ++nIndex;
                }

                if (!silent)
                {
                    Data msgToSend = new Data();
                    msgToSend.cmdCommand = Command.Logout;
                    msgToSend.strMessage = "<<<" + username + " has been kicked from the courtroom>>>";
                    byte[] msg = msgToSend.ToByte();

                    if (clientList.Count > 0)
                    {
                        foreach (ClientInfo clientInfo in clientList)
                        {
                            //Send the message to all users
                            clientInfo.socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(OnSend), clientInfo.socket);
                        }
                    }

                    appendTxtLogSafe(msgToSend.strMessage + "\r\n");
                }

                userNumStat.Text = "Users Online: " + clientList.Count;
            }
        }
Exemplo n.º 14
0
        private void banUser()
        {
            if (lstUsers.SelectedItem != null)
            {
                string IP = ((string)lstUsers.SelectedItem).Split(new string[] { " - " }, StringSplitOptions.None)[1];
                int nIndex = 0;
                foreach (ClientInfo client in clientList)
                {
                    if (client.socket.RemoteEndPoint.ToString().Split(':')[0] == IP)
                    {
                        if (!File.Exists("base/banlist.ini"))
                        {
                            File.CreateText("base/banlist.ini");
                            using (StreamWriter w = new StreamWriter("base/banlist.ini"))
                            {
                                w.WriteLine("[banlist]\r\n");
                            }
                        }

                        bool found = false;
                        using (StreamReader r = new StreamReader("base/banlist.ini"))
                        {
                            while (!r.EndOfStream)
                            {
                                if (r.ReadLine().StartsWith(IP))
                                {
                                    found = true;
                                    break;
                                }

                            }
                        }

                        if (found == false)
                        {
                            using (StreamWriter file = new StreamWriter("base/banlist.ini", true))
                            {
                                file.WriteLine(IP);
                            }
                        }
                        break;
                    }
                    ++nIndex;
                }

                Data msgToSend = new Data();
                msgToSend.cmdCommand = Command.Logout;
                msgToSend.strMessage = "<<<" + ((string)lstUsers.SelectedItem).Split(new string[] { " - " }, StringSplitOptions.None)[0] + " has been banned from the courtroom>>>";
                byte[] msg = msgToSend.ToByte();

                if (clientList.Count > 0)
                {
                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.socket.RemoteEndPoint.ToString().Split(':')[0] != IP)
                        {
                            //Send the message to all users
                            clientInfo.socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(OnSend), clientInfo.socket);
                        }
                    }
                }

                appendTxtLogSafe(msgToSend.strMessage + "\r\n");
                userNumStat.Text = "Users Online: " + clientList.Count;
            }
        }
Exemplo n.º 15
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint epSender = (EndPoint)ipeSender;

                serverSocket.EndReceiveFrom(ar, ref epSender);

                //Transform the array of bytes received from the user into an
                //intelligent form of object Data
                Data msgReceived = new Data(byteData);

                //We will send this object in response the users request
                Data msgToSend = new Data();

                byte[] message;

                //If the message is to login, logout, or simple text message
                //then when send to others the type of the message remains the same
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName = msgReceived.strName;

                switch (msgReceived.cmdCommand)
                {
                    case Command.Login:

                        //When a user logs in to the server then we add her to our
                        //list of clients
                        if (playercount == 0)
                        {
                            player player1 = new player();
                            ClientInfo clientInfo = new ClientInfo();
                            //player player1 = new player();
                            clientInfo.endpoint = epSender;
                            clientInfo.strName = msgReceived.strName;
                            msgToSend.cmdCommand = Command.Login;
                            msgToSend.playerID = playercount;

                            clientList.Add(clientInfo);
                            player1.playerx = 100;
                            player1.playery = 100;
                            player1.playername = msgReceived.strName;
                            player1.playerid = playercount;
                            playerList.Add(player1);
                            playercount = playercount + 1;
                            //Set the text of the message that we will broadcast to all users
                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                            msgToSend.cmdCommand = Command.Login;

                        }
                        else
                        {
                            player player2 = new player();
                            ClientInfo clientInfo = new ClientInfo();
                            clientInfo.endpoint = epSender;
                            clientInfo.strName = msgReceived.strName;
                            msgToSend.playerID = playercount;

                            player2.playerid = playercount;
                            clientList.Add(clientInfo);
                            player2.playerx = 300;
                            player2.playery = 300;
                            player2.playername = msgReceived.strName;
                            player2.playerid = playercount;
                            playerList.Add(player2);

                            playercount = playercount + 1;
                            //Set the text of the message that we will broadcast to all users
                            msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                            msgToSend.cmdCommand = Command.Login;
                        }

                        break;

                    case Command.Create:

                        break;

                    case Command.Logout:

                        //When a user wants to log out of the server then we search for her
                        //in the list of clients and close the corresponding connection

                        int nIndex = 0;
                        foreach (ClientInfo client in clientList)
                        {
                            if (client.endpoint == epSender)
                            {
                                clientList.RemoveAt(nIndex);
                                break;
                            }
                            ++nIndex;
                        }

                        msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the room>>>";
                        break;

                    case Command.Message:

                        //Set the text of the message that we will broadcast to all users
                        msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                        break;

                    case Command.Move:
                        msgToSend = MovePlayer(msgReceived);
                        msgToSend.cmdCommand = msgReceived.cmdCommand;
                        break;
                    case Command.List:

                        //Send the names of all users in the chat room to the new user
                        msgToSend.cmdCommand = Command.List;
                        msgToSend.strName = null;
                        msgToSend.strMessage = null;

                        //Collect the names of the user in the chat room
                        foreach (ClientInfo client in clientList)
                        {
                            //To keep things simple we use asterisk as the marker to separate the user names
                            msgToSend.strMessage += client.strName + "*";
                        }

                        message = msgToSend.ToByte(playerList, playercount);

                        //Send the name of the users in the chat room
                        serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                                new AsyncCallback(OnSend), epSender);
                        break;
                }
                //TODO: Add check to see if it is a login, if it is send the players ID to the client
                //When the client receives the login response it will set the users ID to the correct value
                //
                if (msgToSend.cmdCommand == Command.Login)
                {
                    message = msgToSend.ToByte(playerList, playercount);

                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                            new AsyncCallback(OnSend), epSender);
                    msgToSend.cmdCommand = Command.Create;
                    message = msgToSend.ToByte(playerList, playercount);
                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                            new AsyncCallback(OnSend), epSender);
                    msgToSend.cmdCommand = Command.Login;
                }

                if (msgToSend.cmdCommand != Command.List)   //List messages are not broadcasted
                {
                    message = message = msgToSend.ToByte(playerList, playercount);

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        //Send the message to all users
                        serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                            new AsyncCallback(OnSend), clientInfo.endpoint);
                    }
                }

                //If the user is logging out then we need not listen from her
                //Start listening to the message send by the user
                serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender,
                    new AsyncCallback(OnReceive), epSender);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 16
0
        private Data MovePlayer(Data msgReceived)
        {
            player playermoved = null;
            foreach (player playerp in playerList)
            {
                if (playerp.playerid == msgReceived.playerID)
                {
                    playermoved = playerp;
                }

            }
            Data msgToSend = new Data();
            if (msgReceived.strMessage == "right")
            {
                playermoved.playerx = playermoved.playerx + 1;

            }
            if (msgReceived.strMessage == "left")
            {
                playermoved.playerx = playermoved.playerx - 1;

            }
            if (msgReceived.strMessage == "up")
            {
                playermoved.playery = playermoved.playery - 1;

            }
            if (msgReceived.strMessage == "down")
            {
                playermoved.playery = playermoved.playery + 1;

            }
            return msgToSend;
        }