Exemplo n.º 1
0
        /// <summary>
        /// This function is used to display data in Rich Text Box
        /// </summary>
        /// <param name="text"></param>
        private void SetText(string text)
        {
            //Variable.RECEIVETEXT = text;
            //Console.WriteLine("---" + text);

            if (text.IndexOf("ClientInfo") > 0)
            {
                ClientInfo clientInfo = new ClientInfo(text);
                if (clientInfo.Computer == 1)
                {
                    Variable.RECEIVETEXT1 = text;
                }
                if (clientInfo.Computer == 2)
                {
                    Variable.RECEIVETEXT2 = text;
                }
                if (clientInfo.Computer == 3)
                {
                    Variable.RECEIVETEXT3 = text;
                }
            }
            else if (text.IndexOf("ClockInfo") > 0)
            {
               Variable.RECEIVETEXTCLOCK = text;
            }
        }
Exemplo n.º 2
0
 private void ReSendToClient(ClientInfo client, SendData data)
 {
     WatcherPanelInstance.SendDataToClientWatch(client, data);
 }
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 >>>";
                    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);
                            break;
                        }
                        ++nIndex;
                    }

                    nIndex = 0;
                    foreach (ClientInfo client in audioList)
                    {
                        if (client.endpoint.ToString() == epSender.ToString())
                        {
                            audioList.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.AudioConnect:
                    ClientInfo clientInfo2 = new ClientInfo();
                    clientInfo2.endpoint = epSender;
                    clientInfo2.strName  = msgReceived.strName;

                    audioList.Add(clientInfo2);

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

                case Command.AudioList:
                    msgToSend.cmdCommand = Command.AudioList;
                    msgToSend.strName    = null;
                    msgToSend.strMessage = null;

                    //Collect the names of the user in the chat room
                    foreach (ClientInfo client in audioList)
                    {
                        //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;

                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 && msgToSend.cmdCommand != Command.AudioList)   //List messages are not broadcasted
                {
                    message = msgToSend.ToByte();

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.endpoint != epSender ||
                            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);
                        }
                    }

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


                //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.º 4
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.º 5
0
 public string getClientJson(ClientInfo clientInfo)
 {
     string clientJson = JsonConvert.SerializeObject(clientInfo);
     clientJson = "{\"ClientInfo\":" + clientJson + "}";
     return clientJson;
 }
Exemplo n.º 6
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);
            }
        }
        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);
            }
        }
        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>>>";

                    // Check if the user came in after setting the media
                    if (currentMedia != "")
                    {
                        txtLog.Text += "Sending the new user the current media URL." + "\r\n";
                        Data mediaSend = new Data();
                        mediaSend.strMessage = currentMedia;
                        mediaSend.cmdCommand = Command.MediaURL;
                        byte[] media = mediaSend.ToByte();
                        //Send the name of the users in the chat room
                        serverSocket.BeginSendTo(media, 0, media.Length, SocketFlags.None, epSender,
                                                 new AsyncCallback(OnSend), epSender);
                    }
                    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.MediaURL:
                    currentMedia     = txtMediaURL.Text;
                    txtMediaURL.Text = "";

                    //Send the media URL to all users
                    msgToSend.strMessage = currentMedia;
                    break;

                case Command.Play:
                    // Send the message back to all users
                    msgToSend.strMessage = msgReceived.strMessage;
                    break;

                case Command.Buffering:
                    // Send the message back to all users
                    msgToSend.strMessage = msgReceived.strMessage;
                    break;

                case Command.Time:
                    // Send the message back to all users
                    msgToSend.strMessage = msgReceived.strMessage;
                    break;

                case Command.LocalResync:
                    string[] resync = msgReceived.strMessage.Split('*');
                    if (resync[0] == "1")
                    {
                        // The resyncer wants to resync
                        Data resyncReqSend = new Data();
                        resyncReqSend.strName    = msgReceived.strName;
                        resyncReqSend.strMessage = "2*0*0";
                        resyncReqSend.cmdCommand = Command.LocalResync;
                        byte[] media = resyncReqSend.ToByte();
                        //Send the name of the users in the chat room
                        ClientInfo reqClient = (ClientInfo)clientList[0];
                        serverSocket.BeginSendTo(media, 0, media.Length, SocketFlags.None, reqClient.endpoint,
                                                 new AsyncCallback(OnSend), reqClient.endpoint);
                    }
                    else if (resync[0] == "3")
                    {
                        // The main user sent back a response for the resyncer
                        Data resyncReqSend = new Data();
                        resyncReqSend.strName    = msgReceived.strName;
                        resyncReqSend.strMessage = msgReceived.strMessage;
                        resyncReqSend.cmdCommand = Command.LocalResync;
                        byte[] media = resyncReqSend.ToByte();
                        //Send the name of the users in the chat room
                        ClientInfo reqClient = (ClientInfo)clientList[0];
                        foreach (ClientInfo client in clientList)
                        {
                            if (client.strName == msgReceived.strName)
                            {
                                reqClient = client;
                            }
                        }
                        serverSocket.BeginSendTo(media, 0, media.Length, SocketFlags.None, reqClient.endpoint,
                                                 new AsyncCallback(OnSend), reqClient.endpoint);
                    }
                    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 != epSender ||
                            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);
                        }
                    }

                    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);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Kunomi Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        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.º 10
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.º 11
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   epSender  = (EndPoint)ipeSender;

                serverSocket.EndReceiveFrom(ar, ref epSender);

                var diachiip = epSender.ToString().Split(':')[0];


                // Chuyển mảng byte người nhận
                Data msgReceived = new Data(byteData);

                // Gửi tin nhắn
                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:

                    //Khi một người đăng nhập thì add người đó vào danh sách các client

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

                    clientList.Add(clientInfo);

                    //Gửi tin nhắn tới tất cả các client đã tham gia phòng
                    msgToSend.strMessage = "<<<" + diachiip + " đã tham gia phòng chat>>>";
                    break;

                case Command.Logout:

                    //Khi một người sử dụng muốn đăng xuất thì server sẽ tìm người đó trong danh sách các client và đóng kết nối của client đó

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

                    msgToSend.strMessage = "<<<" + diachiip + " đã rời phòng chat>>>";
                    break;

                case Command.Message:

                    //cài đặt kí tự khi gửi
                    msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                    break;

                case Command.List:

                    //Gửi tên của tất cả các client đến client mới
                    msgToSend.cmdCommand = Command.List;
                    msgToSend.strName    = null;
                    msgToSend.strMessage = null;

                    // lên danh sách tên client
                    foreach (ClientInfo client in clientList)
                    {
                        msgToSend.strMessage += client.strName + "*";
                    }

                    message = msgToSend.ToByte();

                    //gửi lên phòng chat
                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                                             new AsyncCallback(OnSend), epSender);
                    break;
                }

                if (msgToSend.cmdCommand != Command.List)
                {
                    message = msgToSend.ToByte();

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.endpoint != epSender ||
                            msgToSend.cmdCommand != Command.Login)
                        {
                            //Gửi tin nhắn tới tất cả mọi client
                            serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                                                     new AsyncCallback(OnSend), clientInfo.endpoint);
                        }
                    }

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

                //phản hồi từ client khi muốn đăng xuât
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    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.º 12
0
        protected virtual void OnReceive(object sender, ServerSocketReceiveEventArgs e)
        {
            switch (e.Messager.Action)
            {
            case "GetDatabases":
                ClientInfo ci = e.Messager.Arg as ClientInfo;
                if (ci == null)
                {
                    e.AcceptSocket.AccessDenied();
                    debugAppendLog?.Invoke($"AccessDenied(GetDatabases): 连接信息未提供");
                }
                else
                {
                    CodeBuild build = new CodeBuild(ci, e.AcceptSocket);
                    lock (_builds_lock) {
                        _builds.Remove(e.AcceptSocket.Id);
                        _builds.Add(e.AcceptSocket.Id, build);
                    }
                    List <DatabaseInfo> dbs = build.GetDatabases();
                    debugAppendLog?.Invoke("GetDatabases: dbs.Length " + dbs.Count);
                    SocketMessager messager = new SocketMessager(e.Messager.Action, dbs);
                    messager.Id = e.Messager.Id;
                    e.AcceptSocket.Write(messager);
                }
                break;

            case "GetTablesByDatabase":
                string database = string.Concat(e.Messager.Arg);
                if (string.IsNullOrEmpty(database))
                {
                    e.AcceptSocket.AccessDenied();
                    debugAppendLog?.Invoke($"AccessDenied(GetTablesByDatabase): database为空");
                }
                else
                {
                    CodeBuild build = null;
                    if (!_builds.TryGetValue(e.AcceptSocket.Id, out build))
                    {
                        e.AcceptSocket.AccessDenied();
                        debugAppendLog?.Invoke($"AccessDenied(GetTablesByDatabase): _builds.TryGetValue(sockId) 未找到,数据错乱了");
                    }
                    else
                    {
                        List <TableInfo> tables   = build.GetTablesByDatabase(database);
                        SocketMessager   messager = new SocketMessager(e.Messager.Action, tables);
                        messager.Id = e.Messager.Id;
                        e.AcceptSocket.Write(messager);
                    }
                }
                break;

            case "Build":
                object[] parms = e.Messager.Arg as object[];
                if (parms.Length < 4)
                {
                    e.AcceptSocket.AccessDenied();
                    debugAppendLog?.Invoke($"AccessDenied(Build): 参数错误,params.Length < 4");
                }
                else
                {
                    string solutionName = string.Concat(parms[0]);
                    bool   isSolution, isMakeAdmin, isDownloadRes;
                    string op10 = string.Concat(parms[2]);
                    if (string.IsNullOrEmpty(solutionName) ||
                        !bool.TryParse(string.Concat(parms[1]), out isSolution) ||
                        string.IsNullOrEmpty(op10))
                    {
                        e.AcceptSocket.AccessDenied();
                        debugAppendLog?.Invoke($"AccessDenied(Build): -N为空 or -S未使用 or 生成的表列表为空");
                    }
                    else
                    {
                        isMakeAdmin   = false;
                        isDownloadRes = false;
                        if (parms.Length >= 4)
                        {
                            bool.TryParse(string.Concat(parms[3]), out isMakeAdmin);
                        }
                        if (parms.Length >= 5)
                        {
                            bool.TryParse(string.Concat(parms[4]), out isDownloadRes);
                        }
                        CodeBuild build = null;
                        if (!_builds.TryGetValue(e.AcceptSocket.Id, out build))
                        {
                            e.AcceptSocket.AccessDenied();
                            debugAppendLog?.Invoke($"AccessDenied(Build): _builds.TryGetValue(sockId) 未找到,数据错乱了");
                        }
                        else
                        {
                            List <bool> outputs = new List <bool>();
                            char[]      cs      = op10.ToCharArray();
                            foreach (char c in cs)
                            {
                                outputs.Add(c == '1');
                            }
                            build.SetOutput(outputs.ToArray());
                            object parm = null;
                            try {
                                parm = build.Build(solutionName, isSolution, isMakeAdmin, isDownloadRes);
                            } catch (Exception ex) {
                                parm = ex;
                            }
                            SocketMessager messager = new SocketMessager(e.Messager.Action, parm);
                            messager.Id = e.Messager.Id;
                            e.AcceptSocket.Write(messager);
                        }
                    }
                }
                break;

            default:
                e.AcceptSocket.AccessDenied();
                debugAppendLog?.Invoke($"AccessDenied(default): 未实现");
                break;
            }
        }
Exemplo n.º 13
0
        void Receive(object obj)
        {
            Socket     client     = obj as Socket;
            string     clientIP   = client.RemoteEndPoint.ToString().Split(':')[0];
            ClientInfo clientInfo = clientInfoManager.Find(clientIP);

            try
            {
                while (true)
                {
                    byte[] buffer = new byte[BUFFER_SIZE];
                    client.Receive(buffer);

                    DataContainer dataContainer = DataContainer.Deserialize(buffer);

                    switch (dataContainer.Type)
                    {
                    case DataContainerType.SendPcName:

                        string pcName = dataContainer.Data as string;
                        clientInfo.PCName = pcName;
                        clientInfo.Status = ClientInfoStatus.ClientConnected;

                        if (_onClientListChanged != null)
                        {
                            _onClientListChanged(clientInfoManager.Clients);
                        }

                        break;

                    case DataContainerType.SendStudent:
                        Student student1 = dataContainer.Data as Student;

                        clientInfo.StudentInfo = student1;
                        clientInfo.Status      = ClientInfoStatus.StudentConnected;

                        if (_onClientListChanged != null)
                        {
                            _onClientListChanged(clientInfoManager.Clients);
                        }

                        break;

                    case DataContainerType.ThuBai:

                        FileContainer fileNopBaiContainer = dataContainer.Data as FileContainer;

                        string savePath = this.serverPath;

                        if (!Directory.Exists(savePath))
                        {
                            Directory.CreateDirectory(savePath);
                        }

                        string fileName = fileNopBaiContainer.FileInfo.Name;
                        string fullPath = Path.Combine(savePath, fileName);

                        byte[] fileContent = fileNopBaiContainer.FileContent;

                        using (var fileStream = File.Create(fullPath))
                            fileStream.Write(fileContent, 0, fileContent.Length);

                        break;

                    case DataContainerType.SendList:
                        break;

                    case DataContainerType.SendString:
                        break;

                    case DataContainerType.BeginExam:
                        break;

                    case DataContainerType.FinishExam:
                        break;

                    case DataContainerType.LockClient:
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                clientInfo.Status = ClientInfoStatus.Disconnected;

                if (_onClientListChanged != null)
                {
                    _onClientListChanged(clientInfoManager.Clients);
                }

                clientList.Remove(client);
                client.Close();
            }
        }
Exemplo n.º 14
0
 private void DisBindClient(ClientInfo client)
 {
     WatcherPanelInstance.DisBindClient(client);
 }
Exemplo n.º 15
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.º 16
0
 public CodeBuild(ClientInfo client, AcceptSocket socket)
 {
     _client = client;
     _socket = socket;
 }
Exemplo n.º 17
0
 public void BindClient(ClientInfo client)
 {
     WatchingClient = client;
     State          = ClientWatchState.Watching;
     Write(string.Format("设备{0}[{1}:{2}] -> 成功连接", client.ConnId, client.IpAddress, client.Port));
 }
Exemplo n.º 18
0
        private void OnAccept(IAsyncResult ar)
        {
            try
            {
                Socket clientSocket = _serverSocket.EndAccept(ar);

                ClientInfo clientInfo = new ClientInfo(clientSocket);
                clientList.Add(clientInfo);

                //Start listening for more clients
                _serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);

                //Once the client connects then start receiving the commands from her
                clientSocket.BeginReceive(clientInfo.byteData, 0, clientInfo.byteData.Length, SocketFlags.None,
                    new AsyncCallback(OnReceive), clientSocket);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSserverTCP",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 19
0
 public ClientProfile(ClientInfo ci, Socket workSocket) : base(ci)
 {
     WorkSocket = workSocket;
 }
Exemplo n.º 20
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.º 21
0
        // поток для приема подключений
        private static void Listen()
        {
            try
            {
                EndPoint   remoteIp  = new IPEndPoint(IPAddress.Any, 1000); //адрес, с которого пришли данные
                IPEndPoint remoteIP2 = remoteIp as IPEndPoint;

                serverSocket.Bind(remoteIp);  // Привязать этот адрес к серверу

                while (true)
                {
                    StringBuilder builder = new StringBuilder(); // получаем сообщение
                    int           bytes   = 0;                   // количество полученных байтов
                    byte[]        data    = new byte[1024];      // буфер для получаемых данных


                    do
                    {
                        bytes = serverSocket.ReceiveFrom(data, ref remoteIp);
                        string tmp = Encoding.Unicode.GetString(data, 0, bytes);
                        //Console.WriteLine(tmp);
                        builder.Append(tmp);
                    }while (serverSocket.Available > 0);

                    // Преобразование массива байтов, полученных от пользователя, в интеллектуальную форму объекта Data
                    Data msgReceived = new Data(data);

                    // Мы отправим этот объект в ответ на запрос пользователя
                    Data msgToSend = new Data();



                    // Если сообщение предназначено для входа в систему, выхода из системы или простого текстового сообщения, то при отправке другим тип сообщения остается тем же
                    msgToSend.cmdCommand = msgReceived.cmdCommand;
                    msgToSend.strName    = msgReceived.strName;

                    byte[] message;
                    message = msgToSend.ToByte();

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

                        // Когда пользователь входит на сервер, мы добавляем его в наш список клиентов.
                        ClientInfo clientInfo = new ClientInfo();
                        clientInfo.endpoint = remoteIp;
                        clientInfo.strName  = msgReceived.strName;
                        clientList.Add(clientInfo);
                        // Устанавливаем текст сообщения, которое мы будем транслировать всем пользователям
                        msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                        break;

                    case Command.Logout:

                        // Когда пользователь хочет выйти из сервера, мы ищем его в списке клиентов и закрываем соответствующее соединение
                        int nIndex = 0;
                        foreach (ClientInfo client in clientList)
                        {
                            if (client.endpoint == remoteIp)
                            {
                                clientList.RemoveAt(nIndex);
                                break;
                            }
                            ++nIndex;
                        }

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


                    case Command.Message:

                        // Устанавливаем текст сообщения, которое мы будем транслировать всем пользователям
                        msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                        break;

                    case Command.List:
                        // Отправляем имена всех пользователей в чате новому пользователю
                        msgToSend.cmdCommand = Command.List;
                        msgToSend.strName    = null;
                        msgToSend.strMessage = null;

                        // Собираем имена пользователей в чате
                        foreach (ClientInfo client in clientList)
                        {
                            // Для простоты мы используем звездочку в качестве маркера для разделения имен пользователей
                            msgToSend.strMessage += client.strName + "*";
                        }

                        message = msgToSend.ToByte();

                        // Отправить имя пользователя в чате
                        serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, remoteIp, new AsyncCallback(OnSend), remoteIp);
                        break;

                    case Command.Static:

                        Console.Write("Static ");
                        msgToSend.strMessage = "127.0.0.1:1000";

                        data = Encoding.Unicode.GetBytes("127.0.0.1:1000");

                        serverSocket.SendTo(data, remoteIp);

                        break;
                    }


                    // Список сообщений не транслируется
                    if (msgToSend.cmdCommand != Command.List)
                    {
                        message = msgToSend.ToByte();

                        foreach (ClientInfo clientInfo in clientList)
                        {
                            if (clientInfo.endpoint != remoteIp ||
                                msgToSend.cmdCommand != Command.Login)
                            {
                                // Отправить сообщение всем пользователям
                                serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint, new AsyncCallback(OnSend), clientInfo.endpoint);
                            }
                        }
                        Console.WriteLine(msgToSend.strMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Listen");
                Console.ReadKey();
            }
        }
Exemplo n.º 22
0
        public void setFormFromClientJson()
        {
            try
            {
                if (Variable.RECEIVETEXT1 != null)
                {
                    ClientInfo clientInfo1 = new ClientInfo(Variable.RECEIVETEXT1);
                    //Kiểm tra việc có đang chấm hay không?
                    if (clientInfo1.EndMath == 1)
                    {
                        //Đang chấm
                        ChangeSatusMath(lblStatusScoreM1, true);

                        lblStatusScoreM1.Visible = true;
                        lblRefereeM1.Text = clientInfo1.Referee;
                        lblScoreRedM1.Text = clientInfo1.ScoreRed.ToString();
                        lblScoreBlueM1.Text = clientInfo1.ScoreBlue.ToString();
                        lblWinFormM1.Text = clientInfo1.WinForm;
                        ChangeStatus(lblStatusM1, true);

                        //Kiểm tra thắng
                        if (clientInfo1.Win == "RED")
                        {
                            lblPlusRedM1.Visible = true;
                            lblPlusBlueM1.Visible = false;
                        }
                        if (clientInfo1.Win == "BLUE")
                        {
                            lblPlusRedM1.Visible = false;
                            lblPlusBlueM1.Visible = true;
                        }
                       //Variable.RECEIVETEXT1 = null;
                    }
                    //clientInfo1.EndMath == 0
                    else
                    {
                        //Đã chấm xong
                        ChangeSatusMath(lblStatusScoreM1, false);

                        // btnIncRedM1.Visible = true;
                        //btnDecRedM1.Visible = true;
                        // btnIncBlueM1.Visible = true;
                        // btnDecBlueM1.Visible = true;
                    }
                }
                //Không nhận được dữ liệu nữa
                else
                {
                    ChangeStatus(lblStatusM1, false);
                    lblScoreRedM1.Text = "0";
                    lblScoreBlueM1.Text = "0";
                    lblRefereeM1.Text = "-";
                    lblPlusRedM1.Visible = false;
                    lblPlusBlueM1.Visible = false;
                    lblStatusScoreM1.Visible = false;
                }

                //Máy 2
                if (Variable.RECEIVETEXT2 != null)
                {
                    ClientInfo clientInfo2 = new ClientInfo(Variable.RECEIVETEXT2);
                    if (clientInfo2.EndMath == 1)
                    {
                        ChangeSatusMath(lblStatusScoreM2, true);

                        lblStatusScoreM2.Visible = true;
                        lblRefereeM2.Text = clientInfo2.Referee;
                        lblScoreRedM2.Text = clientInfo2.ScoreRed.ToString();
                        lblScoreBlueM2.Text = clientInfo2.ScoreBlue.ToString();
                        lblWinFormM2.Text = clientInfo2.WinForm;
                        ChangeStatus(lblStatusM2, true);

                        if (clientInfo2.Win == "RED")
                        {
                            lblPlusRedM2.Visible = true;
                            lblPlusBlueM2.Visible = false;
                        }
                        if (clientInfo2.Win == "BLUE")
                        {
                            lblPlusRedM2.Visible = false;
                            lblPlusBlueM2.Visible = true;
                        }
                        //Variable.RECEIVETEXT2 = null;
                    }
                    else
                    {
                        ChangeSatusMath(lblStatusScoreM2, false);

                        // btnIncRedM2.Visible = true;
                        //  btnDecRedM2.Visible = true;
                        //  btnIncBlueM2.Visible = true;
                        // btnDecBlueM2.Visible = true;
                    }
                }
                else
                {
                    ChangeStatus(lblStatusM2, false);
                    lblScoreRedM2.Text = "0";
                    lblScoreBlueM2.Text = "0";
                    lblRefereeM2.Text = "-";
                    lblPlusRedM2.Visible = false;
                    lblPlusBlueM2.Visible = false;
                    lblStatusScoreM2.Visible = false;
                }

                //Máy 3
                if (Variable.RECEIVETEXT3 != null)
                {
                    ClientInfo clientInfo3 = new ClientInfo(Variable.RECEIVETEXT3);
                    if (clientInfo3.EndMath == 1)
                    {
                        ChangeSatusMath(lblStatusScoreM3, true);
                        lblStatusScoreM3.Visible = true;
                        lblRefereeM3.Text = clientInfo3.Referee;
                        lblScoreRedM3.Text = clientInfo3.ScoreRed.ToString();
                        lblScoreBlueM3.Text = clientInfo3.ScoreBlue.ToString();
                        lblWinFormM3.Text = clientInfo3.WinForm;
                        ChangeStatus(lblStatusM3, true);

                        if (clientInfo3.Win == "RED")
                        {
                            lblPlusRedM3.Visible = true;
                            lblPlusBlueM3.Visible = false;
                        }
                        if (clientInfo3.Win == "BLUE")
                        {
                            lblPlusRedM3.Visible = false;
                            lblPlusBlueM3.Visible = true;
                        }
                        //Variable.RECEIVETEXT3 = null;
                    }
                    else
                    {
                        ChangeSatusMath(lblStatusScoreM3, false);

                        //btnIncRedM3.Visible = true;
                        //btnDecRedM3.Visible = true;
                        //btnIncBlueM3.Visible = true;
                        //btnDecBlueM3.Visible = true;
                    }
                }
                else
                {
                    ChangeStatus(lblStatusM3, false);
                    lblScoreRedM3.Text = "0";
                    lblScoreBlueM3.Text = "0";
                    lblRefereeM3.Text = "-";
                    lblPlusRedM3.Visible = false;
                    lblPlusBlueM3.Visible = false;
                    lblStatusScoreM3.Visible = false;
                }

                if(Variable.RECEIVETEXTCLOCK!=null)
                {
                    setClockFormClockJson();
                }
                else
                {
                    lblClock.Text = "00:00";
                   lblClock.BackColor = Color.LightGray;
                }

                UpdateScore();
            }
            catch (Exception ex) { }
        }
Exemplo n.º 23
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   epSender  = (EndPoint)ipeSender;

                serverSocket.EndReceiveFrom(ar, ref epSender);

                var diachiip = epSender.ToString().Split(':')[0];
                var portlog  = epSender.ToString().Split(':')[1];


                // Chuyển mảng byte người nhận
                Data msgReceived = new Data(byteData);

                // Gửi tin nhắn
                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:

                    //Khi một người đăng nhập thì add người đó vào danh sách các client

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

                    // Code check trùng ip tên sever
                    string content   = "";
                    var    chuoiip   = clientInfo.endpoint.ToString().Split(':')[0];
                    var    chuoiport = clientInfo.endpoint.ToString().Split(':')[1];
                    if (clientList.Count != 0 && clientList.Count <= 10)
                    {
                        foreach (ClientInfo client in clientList)
                        {
                            var ipclient = client.endpoint.ToString().Split(':')[0];
                            if (ipclient != chuoiip)
                            {
                                clientList.Add(clientInfo);
                                msgToSend.strMessage = "<<<" + diachiip + " đã tham gia phòng chat>>>";
                                content = DateTime.Now.ToString("HH:mm dd/MM/yyyy") + "- người dùng có địa chỉ ip là: " + chuoiip + ", port: " + chuoiport + " đã kết nối vào cuộc trò chuyện";
                            }
                            else
                            {
                                msgToSend.strMessage = "-- Đã chặn người dùng : " + clientInfo.strName + " do trùng IP : " + diachiip + "--";
                            }
                        }
                    }
                    else if (clientList.Count > 10)
                    {
                        msgToSend.strMessage = "-- Đã chặn người dùng : " + clientInfo.strName + " do hệ thống giới hạn lượt truy cập là: 10 người --";
                        content = DateTime.Now.ToString("HH:mm dd/MM/yyyy") + "- người dùng có địa chỉ ip là: " + chuoiip + ", port: " + chuoiport + " đã bị chặn kết nối do quá 10 kết nối tới server";
                    }
                    else
                    {
                        clientList.Add(clientInfo);
                        msgToSend.strMessage = "<<<" + diachiip + " đã tham gia phòng chat>>>";
                        content = DateTime.Now.ToString("HH:mm dd/MM/yyyy") + "- người dùng có địa chỉ ip là: " + chuoiip + ", port: " + chuoiport + " đã kết nối vào cuộc trò chuyện";
                    }
                    // hêts
                    // Lưu lịch sử vào file

                    string path = @"D:\\access.log";
                    if (!System.IO.File.Exists(path))
                    {
                        using (StreamWriter sw = System.IO.File.CreateText(path))
                        {
                            sw.WriteLine(content);
                            sw.Flush();
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = new StreamWriter(path, true))
                        {
                            sw.WriteLine(content);
                            sw.Flush();
                            sw.Close();
                        }
                    }


                    //Gửi tin nhắn tới tất cả các client đã tham gia phòng

                    break;

                case Command.Logout:

                    //Khi một người sử dụng muốn đăng xuất thì server sẽ tìm người đó trong danh sách các client và đóng kết nối của client đó

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

                    msgToSend.strMessage = "<<<" + diachiip + " đã rời phòng chat>>>";
                    // Lưu lịch sử vào file
                    var    content1 = DateTime.Now.ToString("HH:mm dd/MM/yyyy") + "- người dùng có địa chỉ ip là: " + diachiip + ", port: " + portlog + " đã ngắt kết nối tới cuộc trò chuyện";
                    string path1    = @"D:\\access.log";
                    if (!System.IO.File.Exists(path1))
                    {
                        using (StreamWriter sw = System.IO.File.CreateText(path1))
                        {
                            sw.WriteLine(content1);
                            sw.Flush();
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = new StreamWriter(path1, true))
                        {
                            sw.WriteLine(content1);
                            sw.Flush();
                            sw.Close();
                        }
                    }

                    break;

                case Command.Message:

                    //cài đặt kí tự khi gửi
                    msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                    break;

                case Command.List:

                    //Gửi tên của tất cả các client đến client mới
                    msgToSend.cmdCommand = Command.List;
                    msgToSend.strName    = null;
                    msgToSend.strMessage = null;

                    // lên danh sách tên client
                    foreach (ClientInfo client in clientList)
                    {
                        msgToSend.strMessage += client.strName + "*";
                    }

                    message = msgToSend.ToByte();

                    //gửi lên phòng chat
                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                                             new AsyncCallback(OnSend), epSender);
                    break;
                }

                if (msgToSend.cmdCommand != Command.List)
                {
                    message = msgToSend.ToByte();

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.endpoint != epSender ||
                            msgToSend.cmdCommand != Command.Login)
                        {
                            //Gửi tin nhắn tới tất cả mọi client
                            serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                                                     new AsyncCallback(OnSend), clientInfo.endpoint);
                        }
                    }

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

                //phản hồi từ client khi muốn đăng xuât
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    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);
            }
        }