ToByte() public method

Converts the Data structure into an array of bytes
public ToByte ( List playerList, List bulletList, List removeids, int playercount, List planetList ) : byte[]
playerList List A list that contains the players instance
bulletList List A list that contains the Bullets instance
removeids List A list that contains the id of the object removed
playercount int The number of player currently in the game
planetList List A list that contains the Planets instance
return byte[]
コード例 #1
0
ファイル: Form1.cs プロジェクト: tomasdiaz123/Server
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   epSender  = (EndPoint)ipeSender;

                serverSocket.EndReceiveFrom(ar, ref epSender);

                //Transformar o array de bytes recebido do utilizador num objecto de dados
                Data msgReceived = new Data(byteData);
                //Enviar o objecto em resposta aos pedidos dos clientes
                Data msgToSend = new Data();

                byte[] message;
                message = msgToSend.ToByte();
                if (msgReceived.cmdCommand == Command.Login)
                {
                    ClientInfo clientI = new ClientInfo();
                    clientI.strName  = msgReceived.strName;
                    clientI.endpoint = epSender;
                    clientList.Add(clientI);
                }
                if (msgReceived.cmdCommand == Command.Atacar)
                {
                    foreach (ClientInfo clientI in clientList)
                    {
                        if (clientI.strName != msgReceived.strName)
                        {
                            msgToSend.strMessage = msgReceived.strMessage;
                            msgToSend.cmdCommand = msgReceived.cmdCommand;
                            msgToSend.strName    = clientI.strName;
                            message = msgToSend.ToByte();
                            //Enviar a posição ao client 2 depois clienmt 2 ve se acerta se ss message = Acertou!
                            serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientI.endpoint,
                                                     new AsyncCallback(OnSend), clientI.endpoint);
                        }
                    }
                }



                //Se o utilizador saiu, não é necessário continuar a aguardar dados
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    //Aguardar dados do cliente
                    serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender,
                                                  new AsyncCallback(OnReceive), epSender);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Servidor", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #2
0
        public void Joga()
        {
            int    jogador;
            int    palavra;
            Data   msgReceived = new Data(byteData);
            Data   msgToSend   = new Data();
            Random rdn         = new Random();

            byte[] message;
            if (clientList.Count > 2)
            {
                do
                {
                    jogador = rdn.Next(clientList.Count);
                }while (jogador == jogadorAnt);
            }
            else
            {
                jogador = rdn.Next(clientList.Count);
            }
            jogadorAnt = jogador;
            for (int idx = 0; idx < clientList.Count; idx++)
            {
                ClientInfo clientInfo = (ClientInfo)clientList[idx];
                msgToSend.cmdCommand = Command.Null;
                msgToSend.strName    = clientInfo.strName;
                if (idx == jogador)
                {
                    msgToSend.strMessage = "Joga";
                }
                else
                {
                    msgToSend.strMessage = "Não Joga";
                }
                txtLog.Text += msgToSend.strMessage + " " + msgToSend.strName + "\r\n";
                message      = msgToSend.ToByte();
                serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                                         new AsyncCallback(OnSend), clientInfo.endpoint);
            }
            palavra      = rdn.Next(palavras.Length);
            SelectedWord = palavras[palavra];
            txtLog.Text += "Palavra: " + SelectedWord;
        }
コード例 #3
0
        async void ServerWindow_Closing(object sender, CancelEventArgs e)
        {
            if (clientList.Count > 0)
            {
                //Event leállítás
                e.Cancel = true;

                //Read in closed value
                CloseReadDelegate closeRead = new CloseReadDelegate(GetCloseStarted);
                bool closeStarted           = (bool)this.Dispatcher.Invoke(DispatcherPriority.Normal, closeRead);

                //Ha még nincs elindítva, elindítom
                if (!closeStarted)
                {
                    //Kilépés elindítva
                    CloseWriteDelegate closeSet = new CloseWriteDelegate(SetCloseStarted);
                    await this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, closeSet, true);

                    //Kilépési adat
                    Data msgToSend = new Data();
                    msgToSend.cmdCommand = Command.Close;
                    msgToSend.strName    = Data.SERVER_NAME;
                    msgToSend.strRec     = Data.PUBLIC_ID;
                    msgToSend.strMessage = "<<<A szerver bezar>>>";
                    byte[] message = msgToSend.ToByte();

                    //Minden felhasználónak elküldöm
                    foreach (ClientInfo clientInfo in clientList)
                    {
                        clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                                    new AsyncCallback(OnSend), clientInfo.socket);
                    }
                }
                else
                {
                    new Thread(() =>
                    {
                        MessageBox.Show("Várakozás a kliensek lecsatlakozására.");
                    }).Start();
                }
            }
        }
コード例 #4
0
ファイル: ServerForm.cs プロジェクト: jpmac26/AODX
        private void kickUser(bool silent = false)
        {
            if (lstUsers.SelectedItem != null)
            {
                string username = ((string)lstUsers.SelectedItem).Split(new string[] { " - " }, StringSplitOptions.None)[0];
                int nIndex = 0;
                foreach (ClientInfo client in clientList)
                {
                    if (client.strName == username)
                    {
                        clientList.RemoveAt(nIndex);
                        //removeLstUsersSafe(client.strName + " - " + client.character);
                        removeLstUsersSafe(client.strName + " - " + ((IPEndPoint)client.socket.RemoteEndPoint).Address.ToString());
                        client.socket.Close();
                        break;
                    }
                    ++nIndex;
                }

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

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

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

                userNumStat.Text = "Users Online: " + clientList.Count;
            }
        }
コード例 #5
0
        private void queueVideoBtn_Click(object sender, EventArgs e)
        {
            Data msgToSend = new Data();

            byte[] message;

            //Send the media URL to all users
            msgToSend.strMessage = txtMediaURL.Text;
            msgToSend.cmdCommand = Command.MediaURL;
            currentMedia         = txtMediaURL.Text;

            message = msgToSend.ToByte();

            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);
            }

            txtLog.Text += msgToSend.strMessage + "\r\n";
        }
コード例 #6
0
        public void progressBar()
        {
            Data msgReceived = new Data(byteData);
            Data msgToSend   = new Data();

            byte[] message;
            msgToSend.strMessage = progBar.ToString();
            msgToSend.cmdCommand = Command.Prog;
            message = msgToSend.ToByte();
            foreach (ClientInfo clientInfo in clientList)
            {
                serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                                         new AsyncCallback(OnSend), clientInfo.endpoint);
            }
            if (progBar > 0)
            {
                progBar -= 20;
            }
            else
            {
                progBar = 100;
            }
        }
コード例 #7
0
        public void Atualiza()
        {
            Data msgReceived = new Data(byteData);
            Data msgToSend   = new Data();

            byte[] message;
            msgToSend.cmdCommand = Command.List;
            msgToSend.strName    = msgReceived.strName;
            msgToSend.strMessage = null;

            //Colecção de utilizadores no c hat
            foreach (ClientInfo client in clientList)
            {
                //utiliza-se o símbolo (   *   ) para separar os nomes
                msgToSend.strMessage += client.strName + " - Pontos: " + client.pontos + "*";
            }

            message = msgToSend.ToByte();
            foreach (ClientInfo client in clientList)
            {
                serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, client.endpoint,
                                         new AsyncCallback(OnSend), client.endpoint);
            }
        }
コード例 #8
0
ファイル: ServerForm.cs プロジェクト: jpmac26/AODX
        private void banUser()
        {
            if (lstUsers.SelectedItem != null)
            {
                string IP = ((string)lstUsers.SelectedItem).Split(new string[] { " - " }, StringSplitOptions.None)[1];
                int nIndex = 0;
                foreach (ClientInfo client in clientList)
                {
                    if (client.socket.RemoteEndPoint.ToString().Split(':')[0] == IP)
                    {
                        if (!File.Exists("base/banlist.ini"))
                        {
                            File.CreateText("base/banlist.ini");
                            using (StreamWriter w = new StreamWriter("base/banlist.ini"))
                            {
                                w.WriteLine("[banlist]\r\n");
                            }
                        }

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

                            }
                        }

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

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

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

                appendTxtLogSafe(msgToSend.strMessage + "\r\n");
                userNumStat.Text = "Users Online: " + clientList.Count;
            }
        }
コード例 #9
0
ファイル: SGSserverForm.cs プロジェクト: iukash/TcpServerChat
        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);
            }
        }
コード例 #10
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);
                }
        }
コード例 #11
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                Socket clientSocket = (Socket)ar.AsyncState;
                clientSocket.EndReceive(ar);

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

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

                byte[] message;

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

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

                    //Check if the user is authorized for access
                    User connectedUser = new User(msgReceived.strName, msgReceived.strMessage);
                    if (connectedUser.SearchInList(_users) >= 0)
                    {
                        //When a user logs in to the server then we add her to our
                        //list of clients
                        msgToSend.cmdCommand = Command.Accept;
                        //message = msgToSend.ToByte();
                        //clientSocket.Send(message);

                        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 + " csatlakozott a szobahoz>>>";
                    }
                    else
                    {
                        //Decline the user
                        msgToSend.cmdCommand = Command.Decline;
                        msgToSend.strName    = msgReceived.strName;
                        msgToSend.strMessage = null;
                        message = msgToSend.ToByte();

                        //Log it only on the server-side
                        UpdateDelegate update = new UpdateDelegate(UpdateMessage);
                        this.textBox1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, update,
                                                             "<<<" + msgReceived.strName + " megprobalt a szobahoz csatlakozni engedely nelkul>>>" + "\r\n");

                        //Send the message and close the connection
                        clientSocket.Send(message, 0, message.Length, SocketFlags.None);
                        clientSocket.Shutdown(SocketShutdown.Both);
                        clientSocket.Close();
                    }

                    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 && client.strName.Equals(msgReceived.strName))
                        {
                            clientList.RemoveAt(nIndex);
                            break;
                        }
                        ++nIndex;
                    }

                    //Send ack data before closing - Only for the disconnectiong client
                    //msgToSend.cmdCommand = Command.Logout;
                    //msgToSend.strName = msgReceived.strName;
                    msgToSend.strMessage = null;        //A parancs és név marad, az üzenet törlődik.
                    message = msgToSend.ToByte();
                    clientSocket.Send(message, 0, message.Length, SocketFlags.None);

                    //Kapcsolat leállítása
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();

                    msgToSend.strMessage = "<<<" + msgReceived.strName + " elhagyta a szobat>>>";
                    break;

                case Command.Message:

                    //Set the text of the message that we will broadcast to all  (if public)
                    msgToSend.strMessage = msgReceived.strName + " -> " +
                                           (msgReceived.strRec.Equals(Data.PUBLIC_ID) ? "Mindenki" : msgReceived.strRec) +
                                           " : " + msgReceived.strMessage;
                    break;

                case Command.Upload:
                    //Get the correct IP
                    IPEndPoint upEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;

                    //Create a delegate for upload handling
                    string pathUp = Data.FILES_FOLDER + (msgReceived.strRec.Equals(Data.PUBLIC_ID) ? Data.PUBLIC_ID : (msgReceived.strName + "-" + msgReceived.strRec));
                    Directory.CreateDirectory(pathUp);
                    UploadDelegate upload = new UploadDelegate(BeginUpload);
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                upload, upEndPoint.Address, pathUp + "\\" + msgReceived.strMessage, msgReceived.strName, msgReceived.strRec);

                    msgToSend.strMessage = "<<<" + msgReceived.strName + " megkezdte a '" + System.IO.Path.GetFileName(msgReceived.strMessage) + "' nevu falj feltolteset>>>";

                    break;

                case Command.StartDownload:
                    //Get the correct IP
                    IPEndPoint downEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;

                    //Delete message
                    msgToSend.strMessage = null;

                    //Create a delegate for upload handling
                    string pathDown = Data.FILES_FOLDER + (msgReceived.strName.Equals(Data.PUBLIC_ID) ? Data.PUBLIC_ID : (msgReceived.strName + "-" + msgReceived.strRec));
                    Directory.CreateDirectory(pathDown);
                    DownloadDelegate download = new DownloadDelegate(BeginDownload);
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                download, downEndPoint.Address, pathDown + "\\" + msgReceived.strMessage);

                    msgToSend.strMessage = "<<<" + msgReceived.strRec + " megkezdte a '" + System.IO.Path.GetFileName(msgReceived.strMessage) + "' nevu falj letolteset>>>";

                    break;

                case Command.DownloadAck:

                    //Set the text of the message that we will broadcast to all  (if public)
                    msgToSend.strMessage = "<<<" + msgReceived.strRec + " befejezte a '" + System.IO.Path.GetFileName(msgReceived.strMessage) + "' nevu falj letolteset>>>";
                    break;

                case Command.DownloadList:
                    //Delete message
                    msgToSend.strMessage = null;

                    //Create a delegate for upload handling
                    string pathDirectory = Data.FILES_FOLDER + (msgReceived.strRec.Equals(Data.PUBLIC_ID) ? Data.PUBLIC_ID : (msgReceived.strRec + "-" + msgReceived.strName));
                    Directory.CreateDirectory(pathDirectory);

                    //Collect all filenames
                    bool notFirstDownFiles = false;
                    foreach (string file in Directory.GetFiles(pathDirectory))
                    {
                        if (notFirstDownFiles)
                        {
                            msgToSend.strMessage += "*";
                        }
                        else
                        {
                            notFirstDownFiles = true;
                        }
                        msgToSend.strMessage += System.IO.Path.GetFileName(file);
                    }

                    message = msgToSend.ToByte();

                    //Send the filenames
                    clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                           new AsyncCallback(OnSend), clientSocket);

                    break;

                case Command.List:

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

                    //Collect the names of the user in the chat
                    bool notFirstList = false;
                    foreach (ClientInfo client in clientList)
                    {
                        //To keep things simple we use asterisk as the marker to separate the user names
                        if (notFirstList)
                        {
                            msgToSend.strMessage += "*";
                        }
                        else
                        {
                            notFirstList = true;
                        }
                        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 || msgToSend.cmdCommand == Command.DownloadList || msgToSend.cmdCommand == Command.Decline))     //List and decline messages are not broadcasted
                {
                    message = msgToSend.ToByte();

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.socket != clientSocket || msgToSend.cmdCommand != Command.Login)
                        {
                            //A publikus az broadcast, amúgy csak a 2 partnernek megy. -> Figyelni kell, hogy PUBLIC legyen alapból a cél, és feladó is legyen mindig.
                            if (msgToSend.strRec.Equals(Data.PUBLIC_ID) || clientInfo.strName.Equals(msgReceived.strRec) || clientInfo.strName.Equals(msgReceived.strName))
                            {
                                //Send the message to all users
                                clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                                            new AsyncCallback(OnSend), clientInfo.socket);
                                //clientInfo.socket.Send(message, 0, message.Length, SocketFlags.None);
                            }
                        }
                    }

                    UpdateDelegate update = new UpdateDelegate(UpdateMessage);
                    this.textBox1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, update,
                                                         msgToSend.strMessage + "\r\n");
                }

                //If the user is logging out or declined, then we need not listen from her
                if (!(msgReceived.cmdCommand == Command.Logout || msgToSend.cmdCommand == Command.Decline))
                {
                    //Start listening to the message send by the user
                    clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
                }

                //Check if it's the last logout
                if (msgReceived.cmdCommand == Command.Logout && clientList.Count <= 0)
                {
                    //Check if we started a close
                    CloseReadDelegate closeRead = new CloseReadDelegate(GetCloseStarted);
                    bool closeStarted           = (bool)this.Dispatcher.Invoke(DispatcherPriority.Normal, closeRead);

                    //Finish the close
                    if (closeStarted)
                    {
                        CloseDelegate closeRun = new CloseDelegate(CloseRun);
                        this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, closeRun);
                    }
                }
            }
            catch (Exception ex)
            {
                new Thread(() =>
                {
                    MessageBox.Show(ex.Message, "Server Receive");
                }).Start();
            }
        }
コード例 #12
0
ファイル: SGSserverForm.cs プロジェクト: KinTT/DrawerChat
        private void тестToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _testResult = 0;
            _flagTest = 0;

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

            msgToSend.cmdCommand = Command.TestPackageRecieve;
            SendToAll(msgToSend.ToByte());
        }
コード例 #13
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   epSender  = ipeSender;

                serverSocket.EndReceiveFrom(ar, ref epSender);

                Data msgReceived = new Data(byteData);

                byte[] message;

                Data msgToSend = new Data
                {
                    cmdCommand = msgReceived.cmdCommand,
                    userName   = msgReceived.userName
                };

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

                    ClientInfo clientInfo = new ClientInfo
                    {
                        endpoint = epSender,
                        UserName = msgReceived.userName
                    };

                    clientList.Add(clientInfo);

                    msgToSend.strMessage = "[+] " + msgReceived.userName + " has joined the room.";
                    break;

                case Command.Logout:

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

                    msgToSend.strMessage = "[-] " + msgReceived.userName + " has left the room.";
                    break;

                case Command.Message:
                    msgToSend.strMessage = msgReceived.userName + ": " + msgReceived.strMessage;
                    break;

                case Command.List:
                    msgToSend.cmdCommand = Command.List;
                    msgToSend.userName   = null;
                    msgToSend.strMessage = null;

                    foreach (ClientInfo client in clientList)
                    {
                        msgToSend.strMessage += client.UserName + "*";
                    }

                    message = msgToSend.ToByte();

                    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)
                        {
                            serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                                                     new AsyncCallback(OnSend), clientInfo.endpoint);
                        }
                    }

                    txtUsers.Text += msgToSend.strMessage + "\r\n";
                }
                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, "Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #14
0
ファイル: SGSserverForm.cs プロジェクト: KinTT/DrawerChat
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                //We will send this object in response the users request
                Data msgToSend = new Data();

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

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

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

                ClientInfo currentClient = null;

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

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

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

                byte [] message;

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

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

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

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

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

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

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

                        message = msgToSend.ToByte();

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

                    }
                }

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

                            SendToAll(msgToSend.ToByte());
                            break;

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

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

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

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

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

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

                        case Command.ClientList:

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

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

                            message = msgToSend.ToByte();

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

                        case Command.TestPackageRecieve:
                            mut.WaitOne();

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

                            mut.ReleaseMutex();
                            break;
                    }
                }

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

                serverSocket.EndReceiveFrom(ar, ref epSender);

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

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

                byte[] message;

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

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

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

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

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

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

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

                        break;

                    case Command.Create:

                        break;

                    case Command.Logout:

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

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

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

                    case Command.Message:

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

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

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

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

                        message = msgToSend.ToByte(playerList, playercount);

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

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

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

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

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

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #16
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);
            }
        }
コード例 #17
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 he/she added to the list of clients

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

                    clientList.Add(clientInfo);

                    MemoryStream strm = new MemoryStream();
                    BinaryWriter wrt  = new BinaryWriter(strm);
                    wrt.Write(msgReceived.strName);
                    strm.Seek(0, SeekOrigin.Begin);

                    //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 == 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.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, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #18
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   epSender  = (EndPoint)ipeSender;

                serverSocket.EndReceiveFrom(ar, ref epSender);

                //Transformar o array de bytes recebido do utilizador num objecto de dados
                Data msgReceived = new Data(byteData);

                //Enviar o objecto em resposta aos pedidos dos clientes
                Data msgToSend = new Data();

                byte [] message;

                //Controlar o tipo de mensagem (login, logout, ou apenas texto)
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName    = msgReceived.strName;
                switch (msgReceived.cmdCommand)
                {
                case Command.Login:

                    //Quando um cliente se liga, é adicionado à lista de
                    ClientInfo clientInfo = new ClientInfo();
                    clientInfo.endpoint = epSender;
                    clientInfo.strName  = msgReceived.strName;
                    txtLog.Text        += clientInfo.strName + "\r\n";
                    clientList.Add(clientInfo);
                    //Mensagem que vai ser enviada para todos os utilizadores

                    msgToSend.cmdCommand = Command.List;
                    msgToSend.strMessage = "";

                    //Colecção de utilizadores no chat
                    foreach (ClientInfo client in clientList)
                    {
                        //utiliza-se o símbolo (   *   ) para separar os nomes
                        msgToSend.strMessage += client.strName + " - Pontos: " + client.pontos + "*";
                    }

                    message = msgToSend.ToByte();
                    foreach (ClientInfo client in clientList)
                    {
                        serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, client.endpoint,
                                                 new AsyncCallback(OnSend), client.endpoint);
                    }
                    break;

                case Command.Logout:

                    //Quando um cliente se quer desconectar, faz-se a pesquisa do mesmo na lista e termina a ligação correspondente

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

                    msgToSend.strMessage = msgReceived.strName + " saiu!";
                    break;

                case Command.Message:
                    //Mensagem que vai ser enviada para todos os utilizadores
                    msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                    msgToSend.cmdCommand = Command.Message;
                    message = msgToSend.ToByte();
                    foreach (ClientInfo client in clientList)
                    {
                        serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                                                 new AsyncCallback(OnSend), epSender);
                    }
                    if (msgReceived.strMessage == SelectedWord)
                    {
                        msgToSend.strMessage = msgReceived.strName + ": acertou!";
                        msgToSend.cmdCommand = Command.Message;
                        message = msgToSend.ToByte();
                        foreach (ClientInfo client in clientList)
                        {
                            serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                                                     new AsyncCallback(OnSend), epSender);
                        }
                        for (int idx = 0; idx < clientList.Count; idx++)
                        {
                            ClientInfo client = (ClientInfo)clientList[idx];
                            client.pontos++;
                            if (client.strName == msgReceived.strName)
                            {
                                clientList[idx] = client;
                            }
                        }
                    }
                    break;

                case Command.List:

                    //Enviar a lista de utilizadores ao novo cliente
                    msgToSend.cmdCommand = Command.List;
                    msgToSend.strMessage = "";

                    //Colecção de utilizadores no chat
                    foreach (ClientInfo client in clientList)
                    {
                        //utiliza-se o símbolo (   *   ) para separar os nomes
                        msgToSend.strMessage += client.strName + "*";
                    }

                    message = msgToSend.ToByte();
                    foreach (ClientInfo client in clientList)
                    {
                        serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, client.endpoint,
                                                 new AsyncCallback(OnSend), client.endpoint);
                    }
                    //Enviar o nome dos utilizadores no chat

                    break;
                }

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

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.endpoint != epSender ||
                            msgToSend.cmdCommand != Command.Login)
                        {
                            //Enviar mensagem a todos os clientes
                            serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                                                     new AsyncCallback(OnSend), clientInfo.endpoint);
                        }
                    }

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

                //Se o utilizador saiu, não é necessário continuar a aguardar dados
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    //Aguardar dados do cliente
                    serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender,
                                                  new AsyncCallback(OnReceive), epSender);
                }
                Atualiza();
                if (clientList.Count > 0 && SelectedWord == "")
                {
                    timerProgBar.Stop();
                }
                else
                {
                    timerProgBar.Stop();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Servidor", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #19
0
ファイル: SGSserverForm.cs プロジェクト: KinTT/DrawerChat
        private void OnReceiveRegistrate(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint epSender = (EndPoint)ipeSender;

                _publicSocket.EndReceive(ar, ref ipeSender);

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

                byte[] message;

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

                message = msgToSend.ToByte();

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

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

                //Start listening to the message send by the user
                _publicSocket.BeginReceive(new AsyncCallback(OnReceiveRegistrate), ipeSender);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #20
0
ファイル: ServerForm.cs プロジェクト: jpmac26/AODX
        private void kickUser(bool silent = false)
        {
            if (lstUsers.SelectedItem != null)
            {
                string username = ((string)lstUsers.SelectedItem).Split(new string[] { " - " }, StringSplitOptions.None)[0];
                int nIndex = 0;
                foreach (ClientInfo client in clientList)
                {
                    if (client.strName == username)
                    {
                        clientList.RemoveAt(nIndex);
                        //removeLstUsersSafe(client.strName + " - " + client.character);
                        removeLstUsersSafe(client.strName + " - " + ((IPEndPoint)client.socket.RemoteEndPoint).Address.ToString());
                        client.socket.Close();
                        break;
                    }
                    ++nIndex;
                }

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

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

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

                userNumStat.Text = "Users Online: " + clientList.Count;
            }
        }
コード例 #21
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                Socket clientSocket = (Socket)ar.AsyncState;
                clientSocket.EndReceive(ar);

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

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

                byte [] message;

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

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

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

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

                    clientList.Add(clientInfo);

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

                case Command.Logout:

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

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

                    clientSocket.Close();

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

                case Command.Message:

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

                case Command.List:

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

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

                    message = msgToSend.ToByte();

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

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

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

                    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
                    clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ConcordServer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #22
0
ファイル: ServerForm.cs プロジェクト: jpmac26/AODX
        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);
            }
        }
コード例 #23
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);
            }
        }
コード例 #24
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);
            }
        }
コード例 #25
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);

                    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;
                    }

                    break;

                case Command.Message:
                    //myRsa enk = new myRsa();
                    //Console.WriteLine(enk.Dekripto(msgReceived.strMessage));
                    //Set the text of the message that we will broadcast to all users
                    Console.WriteLine(msgReceived.strMessage);
                    msgToSend.strMessage = msgReceived.strName + ": " + myRsa.Decrypt(msgReceived.strMessage);
                    break;
                }

                if (msgToSend.cmdCommand != Command.List)   //List messages are not broadcasted
                {
                    txtLog.Text += msgToSend.strMessage + "\r\n";

                    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);
                        }
                    }
                }

                //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, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #26
0
        /// <summary>
        /// This is the update loop used to constantly update the game objects
        /// checking for collisions, and removing objects
        /// </summary>
        public void Update()
        {
            //Required variables
            byte[] message;
            Player playerbullet = null;
            List<Bullet> toRemove = new List<Bullet>();
            Data msgToSend = new Data();
            //Loop forever
            while (true)
            {
                //Wait 40 ms
                Thread.Sleep(40);

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

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

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

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

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

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

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

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

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

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

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

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

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

                //Loop through all clients
                foreach (ClientInfo clientInfo in clientList)
                {
                    //Send the message to all users
                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint, new AsyncCallback(OnSend), clientInfo.endpoint);
                }
            }//End while loop
        }
コード例 #27
0
        private async void BeginUpload(IPAddress address, string filename, string sender, string receiver)
        {
            //Wait for others to finish
            if (_uploading)
            {
                Thread.Sleep(2000);
            }

            //Set the pooling flag
            _uploading = true;

            try
            {
                var listener = new TcpListener(address, Data.UPLOAD_PORT);
                listener.Start();
                using (var client = await listener.AcceptTcpClientAsync())
                    using (var stream = client.GetStream())
                        using (var output = File.Create(filename))
                        {
                            try
                            {
                                //Console.WriteLine("Client connected. Starting to receive the file.");

                                // read the file in chunks of 1KB
                                var buffer = new byte[1024];
                                int bytesRead;
                                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    output.Write(buffer, 0, bytesRead);
                                }
                            }
                            catch (Exception ex)
                            {
                                new Thread(() =>
                                {
                                    MessageBox.Show(ex.Message, "Server Upload");
                                }).Start();
                            }
                        }
                listener.Stop();
                //Console.WriteLine("Client Disconnected.");
            }
            catch (Exception ex)
            {
                new Thread(() =>
                {
                    MessageBox.Show(ex.Message, "Server Upload Using");
                }).Start();
            }

            _uploading = false;

            //Send an upload ack message
            byte[] message;
            Data   msgToSend = new Data();

            msgToSend.cmdCommand = Command.Message;
            msgToSend.strName    = sender;
            msgToSend.strRec     = receiver;
            msgToSend.strMessage = sender + " -> " +
                                   (receiver.Equals(Data.PUBLIC_ID) ? "Mindenki" : receiver) +
                                   " : '" + System.IO.Path.GetFileName(filename) + "' nevu fajl sikeresen megosztva.";

            message = msgToSend.ToByte();

            try
            {
                foreach (ClientInfo clientInfo in clientList)
                {
                    //A publikus az broadcast, amúgy csak a 2 partnernek megy. -> Figyelni kell, hogy PUBLIC legyen alapból a cél, és feladó is legyen mindig.
                    if (receiver.Equals(Data.PUBLIC_ID) || clientInfo.strName.Equals(sender) || clientInfo.strName.Equals(receiver))
                    {
                        //Send the message to all users
                        clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
                                                    new AsyncCallback(OnSend), clientInfo.socket);
                    }
                }
            }
            catch (Exception ex)
            {
                new Thread(() =>
                {
                    MessageBox.Show(ex.Message, "Server Upload Message");
                }).Start();
            }

            UpdateDelegate update = new UpdateDelegate(UpdateMessage);

            await this.textBox1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, update,
                                                       msgToSend.strMessage + "\r\n");
        }
コード例 #28
0
ファイル: Server.cs プロジェクト: Lucan1/UDPChat
        // поток для приема подключений
        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();
            }
        }
コード例 #29
0
ファイル: ServerForm.cs プロジェクト: jpmac26/AODX
        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);
            }
        }
コード例 #30
0
ファイル: Server.cs プロジェクト: AChocobo/Connect-4
        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);
            }
        }
コード例 #31
0
ファイル: ServerForm.cs プロジェクト: jpmac26/AODX
        private void banUser()
        {
            if (lstUsers.SelectedItem != null)
            {
                string IP = ((string)lstUsers.SelectedItem).Split(new string[] { " - " }, StringSplitOptions.None)[1];
                int nIndex = 0;
                foreach (ClientInfo client in clientList)
                {
                    if (client.socket.RemoteEndPoint.ToString().Split(':')[0] == IP)
                    {
                        if (!File.Exists("base/banlist.ini"))
                        {
                            File.CreateText("base/banlist.ini");
                            using (StreamWriter w = new StreamWriter("base/banlist.ini"))
                            {
                                w.WriteLine("[banlist]\r\n");
                            }
                        }

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

                            }
                        }

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

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

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

                appendTxtLogSafe(msgToSend.strMessage + "\r\n");
                userNumStat.Text = "Users Online: " + clientList.Count;
            }
        }
コード例 #32
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>>>";

                    // 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);
            }
        }
コード例 #33
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);
            }
        }
コード例 #34
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);
            }
        }