예제 #1
0
        // Deserialize a JSON stream to a User object.
        public static GamerList ReadHost(byte[] json)
        {
            try
            {
                string sizeJson = Encoding.UTF8.GetString(json, 0, 6);
                // Payload size
                int size = 0;
                Int32.TryParse(sizeJson, out size);

                // Create an array the size of a useful package
                byte[] jsonAfter = new byte[size];

                // Copy from the initial array to the final only the useful part
                Array.Copy(json, 6, jsonAfter, 0, size);

                string returnData       = Encoding.UTF8.GetString(jsonAfter, 0, jsonAfter.Length);
                var    deserializedUser = new GamerList();
                var    ms  = new MemoryStream(Encoding.UTF8.GetBytes(returnData));
                var    ser = new DataContractJsonSerializer(deserializedUser.GetType());
                deserializedUser = ser.ReadObject(ms) as GamerList;
                ms.Close();
                return(deserializedUser);
            }
            catch
            {
                return(null);
            }
        }
예제 #2
0
        // Create a User object and serialize it to a JSON stream.
        public static byte[] WriteHost(GamerList user)
        {
            try
            {
                // Create a stream to serialize the object to.
                var ms = new MemoryStream();

                // Serializer the User object to the stream.
                var ser = new DataContractJsonSerializer(typeof(GamerList));
                ser.WriteObject(ms, user);
                byte[] json = ms.ToArray();
                ms.Close();

                if (json.Length < 7000)
                {
                    byte[] jsonSize = Encoding.UTF8.GetBytes(json.Length.ToString());

                    byte[] jsonLen = new byte[6 + json.Length];

                    Array.Copy(jsonSize, 0, jsonLen, 0, jsonSize.Length);
                    Array.Copy(json, 0, jsonLen, 6, json.Length);

                    return(jsonLen);
                }
                else
                {
                    return(null);
                }
            }
            catch
            {
                return(null);
            }
        }
예제 #3
0
        public static void SendToNumberThread(int index, GamerList gamerList)

        {
            Thread sendThread = new Thread(delegate() { SendToNumber(index, gamerList); });

            sendThread.Start();
        }
예제 #4
0
        public static void SendAllThread(GamerList gamerList)

        {
            Thread sendThread = new Thread(delegate() { SendAll(gamerList); });

            sendThread.Start();
        }
예제 #5
0
        public static void SendAll(GamerList gamerList)
        {
            Set printData = new Set();

            for (int i = 1; i < Data.GamersList.gamer.Count; i++)
            {
                try
                {
                    tcpStream = tcpClients[i].GetStream();
                    // Buffer array to verify that I'm sending
                    byte[] send = Json.WriteHost(gamerList);

                    if (send != null)
                    {
                        tcpStream.Write(send, 0, send.Length);
                        tcpStream.Flush();
                    }
                    else
                    {
                        Data.GamersList.Message = null;
                    }
                }
                catch
                {
                    RemoveUserNumber(i);
                }
            }
        }
예제 #6
0
        public static void SendToNumber(int index, GamerList gamerList)
        {
            try
            {
                tcpStream = Host.tcpClients[index].GetStream();

                // Sending
                tcpStream.Write(Json.WriteHost(gamerList), 0, Json.WriteHost(gamerList).Length);
                tcpStream.Flush();
            }
            catch { }
        }
예제 #7
0
파일: Client.cs 프로젝트: endrewsmith/TMC
        // Processing messages from players
        private void UpdateLog(GamerList gamerList)
        {
            Set printData     = new Set();
            Set addToDataGrid = new Set();

            switch (gamerList.Type)
            {
            // Update list gamers
            case 0:
            {
                Data.gamerList.Clear();
                Data.GamersList = gamerList;

                // Get your number
                Get getMyNumber = new Get();
                getMyNumber.GetMyNamber();

                // Host sending
                for (int i = 0; i < Data.GamersList.gamer.Count; i++)
                {
                    addToDataGrid.AddToGrid(i);
                }

                // Exit the method
                return;
            }

            // Changing map
            case 1:
            {
                Data.SettingCh.St.Map = gamerList.Map;
                Data.LobbyLink.ShowMap(gamerList.Map);

                // Exit the method
                return;
            }

            // Changing car
            case 2:
            {
                Data.MainWin.Dispatcher.Invoke(new Action(delegate()
                    {
                        Data.GamersList.gamer[gamerList.Number].GCar = gamerList.Map;
                    }));

                // Exit the method
                return;
            }

            // Changing team
            case 11:
            {
                Data.MainWin.Dispatcher.Invoke(new Action(delegate()
                    {
                        Data.GamersList.gamer[gamerList.Number].GTeam = gamerList.Map;
                    }));

                // Exit the method
                return;
            }

            // Changing gamers status
            case 3:
            {
                Data.LobbyLink.Dispatcher.Invoke(new Action(delegate()
                    {
                        Data.GamersList.gamer[gamerList.Number].GStatus = gamerList.Map;

                        if (Data.GamersList.gamer[Data.MyNamber].Status == 0)
                        {
                            Data.LobbyLink.UnLock();
                        }
                        else
                        {
                            Data.LobbyLink.Lock();
                        }

                        if (Data.GamersList.gamer[0].Status != 0 && Data.GamersList.gamer[Data.MyNamber].Status != 0)
                        {
                            Data.BtnReady.IsEnabled     = false;
                            Data.LineBtnReady.IsEnabled = false;
                        }
                        else
                        {
                            Data.BtnReady.IsEnabled     = true;
                            Data.LineBtnReady.IsEnabled = true;
                        }
                    }));

                // Exit the method
                return;
            }

            // Set message from gamer
            case 4:
            {
                Set setMassage = new Set();
                setMassage.SetMassage(gamerList.Number, gamerList.Message);

                // Exit the method
                return;
            }

            // Set message abot already taken car
            case 5:
            {
                Set MassageAboutCar = new Set();
                MassageAboutCar.SetMassageCar(gamerList.Number);

                // Exit the method
                return;
            }

            // Changing score
            case 6:
            {
                Data.SettingCh.St.Score = gamerList.Score;

                Data.MainWin.Dispatcher.Invoke(new Action(delegate()
                    {
                        Data.LobbyLink.ScoreChange(gamerList.Score);
                        Sound.PlaySound("score.mp3");
                    }));

                // Exit the method
                return;
            }

            // Changing UDP ports
            case 7:
            {
                for (int i = 0; i < Data.GamersList.gamer.Count; i++)
                {
                    Data.GamersList.gamer[i].Udp = gamerList.gamer[i].Udp;
                }

                // Exit the method
                return;
            }

            // Start ld.exe
            case 8:
            {
                // Everyone has the same data
                Data.GamersList = gamerList;
                Ld startLd = new Ld();

                Sound.PlaySound("go.mp3");

                startLd.StartLDThread();

                return;
            }

            // Add or leave lobby
            case 9:
            {
                // Everyone has the same data
                Set massageAddLeave = new Set();

                if (gamerList.Message == "add")
                {
                    massageAddLeave.SetMassageAddLeave(true, gamerList.Number);
                }
                else
                {
                    massageAddLeave.SetMassageAddLeave(false, gamerList.Number);
                }

                return;
            }

            // Close connection
            case 10:
            {
                CloseConnection("Connection error", "The host terminated your connection");

                // Exit the method
                return;
            }

            case 12:
            {
                CloseConnection("Connection error", "The lobby is closed");

                // Exit the method
                return;
            }

            // Reboot UDP modul
            case 13:
            {
                // Turn off UDP
                Data.UdpWorkSend = false;
                Data.UdpWorkRec  = false;
                if (Udp.receiver_server != null)
                {
                    Udp.receiver_server.Close();
                }

                // Turn on UDP module
                Udp UdpOn = new Udp();
                UdpOn.StartUDPModul0neSecThread();

                // Exit the method
                return;
            }

            default:
            {
                return;
            }
            }
        }
예제 #8
0
파일: Client.cs 프로젝트: endrewsmith/TMC
        // For receiving mssages
        private void ReceiveMessages()

        {
            int bufferSize = 8000;
            Set printData  = new Set();
            Set setGamer   = new Set();

            // Create a buffer for receiving
            byte[] bytes = new byte[bufferSize];

            _tcpStream = _tcpServer.GetStream();

            try
            {
                int bytesRead = _tcpStream.Read(bytes, 0, bytes.Length);
            }
            catch { }

            GamerList gamerTempList = new GamerList();

            gamerTempList = Json.ReadHost(bytes);

            if (gamerTempList == null)
            {
                MainWin.Message("Connection error", "Connection error");
                // Exit
                return;
            }

            switch (gamerTempList.Type)
            {
            // Error in nikename
            case -4:
            {
                CloseConnection("Connection error", "Invalid characters in name");
                return;
            }

            // Closing room
            case -3:
            {
                CloseConnection("Connection error", "Lobby closed");
                return;
            }

            // Wrong password
            case -2:
            {
                CloseConnection("Connection error", "Wrong password");
                return;
            }

            // Name is already used
            case -1:
            {
                CloseConnection("Connection error", "Your name is already used");
                return;
            }

            // If there are no errors and the request is accepted
            default:
            {
                Data.MainWin.Dispatcher.Invoke(new Action(delegate()
                    {
                        // Create lobby window
                        Data.MainWin.CreateLobby();
                    }));

                // Accept the list of all players
                Data.GamersList = gamerTempList;

                printData.SetMassageInfo("You are logged in as " + Data.SettingCh.St.Name + "\r\n");

                // Display the list in the table
                for (int i = 0; i < Data.GamersList.gamer.Count; i++)
                {
                    setGamer.AddToGrid(i);
                }

                // Get your number
                Get getMyNumber = new Get();
                getMyNumber.GetMyNamber();

                Data.LobbyLink.Dispatcher.Invoke(new Action(delegate()
                    {
                        Get getMap = new Get();

                        // Set map
                        Data.LobbyLink.ShowMap(Data.GamersList.Map);

                        // Set score
                        Data.LobbyLink.ScoreChange(Data.GamersList.Score);

                        // Set header
                        if (Data.JoinToServer)
                        {
                            string name;
                            if (Data.webList[Data.LobbyNumber].Name.Length > 16)
                            {
                                name = Data.webList[Data.LobbyNumber].Name.Substring(0, 16) + "...";
                            }
                            else
                            {
                                name = Data.webList[Data.LobbyNumber].Name;
                            }

                            Data.LobbyLink.Title = name + " [ " + Data.GamersList.ModOrig + " | " + Data.GamersList.LobbyType + " ]";
                        }
                        else
                        {
                            Data.LobbyLink.Title = Data.GamersList.gamer[0].Name + "'s Lobby [ " + Data.GamersList.ModOrig + " | " + Data.GamersList.LobbyType + " ]";
                        }
                    }));

                // Turn on UDP module
                Udp UdpOn = new Udp();
                UdpOn.StartUDPModul();

                srReceiver = new System.IO.StreamReader(_tcpStream);

                // While Connected == true accept messages
                while (Connected)
                {
                    try
                    {
                        int    byteRead;
                        byte[] bytesHost = new byte[bufferSize];

                        byteRead = _tcpStream.Read(bytesHost, 0, bufferSize);

                        if (byteRead != 0)
                        {
                            GamerList gamerList = new GamerList();
                            gamerList = Json.ReadHost(bytesHost);

                            Data.LobbyLink.Dispatcher.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { gamerList });
                        }

                        else
                        {
                            CloseConnection("Connection error", "The lobby is closed by host");
                            return;
                        }
                    }

                    catch { return; }
                }

                return;
            }
            }
        }
예제 #9
0
        // Called when a new customer is accepted
        private void AcceptClient()
        {
            DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(Gamers));

            Set printData = new Set();

            tcpStream = tcpClient.GetStream();
            byte[] bytes = new byte[8000];

            try
            {
                Data.Inf.Dispatcher.Invoke(new Action(delegate()
                {
                    int bytesRead = tcpStream.Read(bytes, 0, bytes.Length);
                }));
            }
            catch { }

            // Checking if I cannot serialize what has come means not to me
            try
            {
                Gamers gamerTest = Json.ReadClient(bytes);
                if (gamerTest == null)
                {
                    // Removes a player when it exits.
                    Host.RemoveUser(tcpClient);
                    return;
                }
            }

            catch { }

            Gamers gamer = Json.ReadClient(bytes);

            // If your ip is not defined, define it
            if (!Host.getMyIp)
            {
                // UDP port FROM FILE for listening from all IPs
                int portUdp = 0;
                Int32.TryParse(Data.SettingCh.St.UdpPort, out portUdp);

                IPEndPoint RemoteEndPoint = null;

                if (gamer.Message != "tcptest" && gamer.Message != null)
                {
                    IPAddress IpHost = IPAddress.Parse(gamer.Message);
                    RemoteEndPoint = new IPEndPoint(IpHost, portUdp);
                    Data.GamersList.gamer[0].Udp = RemoteEndPoint;

                    // If you have determined your IP, then set true
                    Host.getMyIp = true;
                }
                else
                {
                    Set message = new Set();
                    message.SetText("TCP port is open");
                }
            }

            // Objects for serialization
            GamerList gamerList = new GamerList();

            //________________________________ Parsing messages _________________________________\\

            // Initialization message
            if (gamer.Type == 0)
            {
                // If the room is closed, I inform this to the person who sent the request and disconnect the connection

                if (Data.LobbyOpen == false)
                {
                    gamerList.Type = -3;

                    tcpStream.Write(Json.WriteHost(gamerList), 0, Json.WriteHost(gamerList).Length);
                    tcpStream.Flush();
                    CloseConnection();
                    return;
                }


                if (Data.UseLobbyPassword == true)
                {
                    if (gamer.Key != "yes")
                    {
                        if (gamer.Password != Data.SettingCh.St.Password)
                        {
                            gamerList.Type = -2;

                            tcpStream.Write(Json.WriteHost(gamerList), 0, Json.WriteHost(gamerList).Length);
                            tcpStream.Flush();
                            CloseConnection();
                            return;
                        }
                    }
                }

                if (gamer.Name != "" && gamer.Name != null)
                {
                    // Loop through all the names
                    for (int i = 0; i < Data.GamersList.gamer.Count; i++)
                    {
                        if (gamer.Name == Data.GamersList.gamer[i].Name)
                        {
                            gamerList.Type = -1;

                            tcpStream.Write(Json.WriteHost(gamerList), 0, Json.WriteHost(gamerList).Length);
                            tcpStream.Flush();
                            CloseConnection();
                            return;
                        }
                    }
                }

                else
                {
                    gamerList.Type = -4;

                    tcpStream.Write(Json.WriteHost(gamerList), 0, Json.WriteHost(gamerList).Length);
                    tcpStream.Flush();
                    CloseConnection();
                    return;
                }

                // Add the user to the lists and start listening to his messages
                Host.tcpClients.Add(tcpClient);
                Host.AddUser(gamer);

                //________________________________ Parsing other messages _________________________________\\

                try
                {
                    srReceiver = new System.IO.StreamReader(tcpStream);
                    // Peek () here serves as an indicator of client disconnection
                    int buf = 0;
                    Array.Clear(bytes, 0, bytes.Length);

                    // Waiting for a message from the player
                    while ((buf = tcpStream.Read(bytes, 0, bytes.Length)) != 0 || srReceiver.Peek() == -1)

                    {
                        Set printDat = new Set();

                        gamer = Json.ReadClient(bytes);

                        // Change of car
                        if (gamer.Type == 1)
                        {
                            Data.GamersList.gamer[gamer.Number].GCar = gamer.Car;
                            GamerList gamerListCar = new GamerList();
                            gamerListCar.Type   = 2;
                            gamerListCar.Number = gamer.Number;
                            gamerListCar.Map    = gamer.Car;

                            Host.SendAllThread(gamerListCar);
                        }

                        // Team change
                        if (gamer.Type == 2)
                        {
                            Data.GamersList.gamer[gamer.Number].GTeam = gamer.Team;
                            GamerList gamerListTeam = new GamerList();
                            gamerListTeam.Type   = 11;
                            gamerListTeam.Number = gamer.Number;
                            gamerListTeam.Map    = gamer.Team;

                            Host.SendAllThread(gamerListTeam);
                        }

                        // Changed status
                        if (gamer.Type == 3)
                        {
                            // Change status to Not Ready
                            if (gamer.Status == 0)
                            {
                                // Need "approval" of the Host, when he clicked Ready, you can not reset
                                if (Data.GamersList.gamer[0].Status == 0)
                                {
                                    Data.GamersList.gamer[gamer.Number].GStatus = 0;
                                    GamerList gamerListTeam = new GamerList();
                                    gamerListTeam.Type   = 3;
                                    gamerListTeam.Number = gamer.Number;
                                    gamerListTeam.Map    = 0;

                                    Host.SendAllThread(gamerListTeam);
                                }
                            }
                            // If the player sent that Ready
                            else
                            {
                                // Sorting through the cycle of all whose status is ready
                                for (int i = 0; i < Data.GamersList.gamer.Count; i++)
                                {
                                    if (Data.GamersList.gamer[i].Status != 0)
                                    {
                                        if (gamer.Car == Data.GamersList.gamer[i].Car)
                                        {
                                            gamer.Status = 0;
                                            GamerList gamerListMap = new GamerList();
                                            gamerListMap.Type   = 5;
                                            gamerListMap.Number = i;

                                            Host.SendToNumberThread(gamer.Number, gamerListMap);
                                            break;
                                        }
                                    }
                                }

                                Data.GamersList.gamer[gamer.Number].GStatus = gamer.Status;
                                GamerList gamerListTeam = new GamerList();
                                gamerListTeam.Type   = 3;
                                gamerListTeam.Number = gamer.Number;
                                gamerListTeam.Map    = gamer.Status;

                                Host.SendAllThread(gamerListTeam);
                            }

                            // Control the start button
                            Data.LobbyLink.Dispatcher.Invoke(new Action(delegate()
                            {
                                Data.LobbyLink.Go();
                            }));
                        }

                        // Message
                        if (gamer.Type == 4)
                        {
                            Set       setMassage   = new Set();
                            GamerList gamerListMap = new GamerList();
                            gamerListMap.Type    = 4;
                            gamerListMap.Number  = gamer.Number;
                            gamerListMap.Message = gamer.Message;

                            Host.SendAllThread(gamerListMap);

                            setMassage.SetMassage(gamer.Number, gamer.Message);
                        }

                        // Remove player
                        if (gamer.Type == 7)
                        {
                            Host.RemoveUser(tcpClient);
                        }
                    }
                }

                catch { }
            }
        }
예제 #10
0
        // Removing a player over TCP (basic removal)
        public static void RemoveUserNumber(int index)
        {
            Set printData = new Set();

            // If the participant is in the tcp list of clients, then delete it by index
            if (Host.tcpClients.Count >= (index + 1))
            {
                GamerList gamer = new GamerList();
                gamer.Type = 10;
                SendToNumber(index, gamer);

                // First we’ll show that the participant has left the chat
                printData.SetMassageAddLeave(false, index);
                GamerList gamerListAdd = new GamerList();
                gamerListAdd.Type    = 9;
                gamerListAdd.Number  = index;
                gamerListAdd.Message = "leave";
                Host.SendAllThread(gamerListAdd);

                try
                {
                    // Delete all information from the list
                    Data.GamersList.gamer.RemoveAt(index);

                    // If not the last one in the list has left, then I recount the numbers after it
                    if (index != Data.GamersList.gamer.Count)
                    {
                        for (int j = index; j < Data.GamersList.gamer.Count; j++)
                        {
                            Data.GamersList.gamer[j].Number = j;
                        }
                    }

                    // Delete from the table collection
                    Data.ChatStatic.Dispatcher.Invoke(new Action(delegate()
                    {
                        Data.gamerList.Clear();
                        Set addToDataGrid = new Set();
                        // Host sending
                        for (int i = 0; i < Data.GamersList.gamer.Count; i++)
                        {
                            addToDataGrid.AddToGrid(i);
                        }
                    }));
                }
                catch (Exception ex) { }

                if (tcpClients[index] != null)
                {
                    tcpClients[index].Close();
                    tcpClients.RemoveAt(index);
                }

                Data.GamersList.Type = 0;
                Host.SendAllThread(Data.GamersList);

                // Control the start button
                Data.LobbyLink.Dispatcher.Invoke(new Action(delegate()
                {
                    Data.LobbyLink.Go();
                }));
                Data.LobbyLink.Dispatcher.Invoke(new Action(delegate()
                {
                    Data.LobbyLink.CheckPing();
                }));
            }
        }
예제 #11
0
        // Removing a player over TCP (basic removal)
        public static void RemoveUser(TcpClient tcpUser)
        {
            Set print     = new Set();
            Set printData = new Set();

            for (int i = 1; i < Data.GamersList.gamer.Count; i++)
            {
                // If the participant is in the tcp list of clients, then delete it by index
                if (tcpClients[i] == tcpUser)
                {
                    //  First show that the participant has left the chat

                    printData.SetMassageAddLeave(false, i);
                    GamerList gamerListAdd = new GamerList();
                    gamerListAdd.Type    = 9;
                    gamerListAdd.Number  = i;
                    gamerListAdd.Message = "leave";

                    Host.SendAllThread(gamerListAdd);

                    try
                    {
                        // Delete all information from the list
                        Data.GamersList.gamer.RemoveAt(i);

                        // If not the last one in the list has left, then I recount the numbers after it
                        if (i != Data.GamersList.gamer.Count)
                        {
                            for (int j = i; j < Data.GamersList.gamer.Count; j++)
                            {
                                Data.GamersList.gamer[j].Number = j;
                            }
                        }


                        // Delete from the table collection
                        Data.ChatStatic.Dispatcher.Invoke(new Action(delegate()
                        {
                            Data.gamerList.Clear();
                            Set addToDataGrid = new Set();
                            // Host sending
                            for (int gamer = 0; gamer < Data.GamersList.gamer.Count; gamer++)
                            {
                                addToDataGrid.AddToGrid(gamer);
                            }
                        }));
                    }
                    catch (Exception ex) { }

                    if (tcpUser != null)
                    {
                        tcpUser.Close();
                    }

                    if (tcpClients[i] != null)
                    {
                        tcpClients[i].Close();
                        tcpClients.RemoveAt(i);
                    }

                    Get closingOrNotLobby = new Get();

                    // Open the lobby if the player leaves the lobby himself, if he doesn’t open, the lobby will not open
                    closingOrNotLobby.GetClosingLobby();

                    Data.GamersList.Type = 0;
                    Host.SendAllThread(Data.GamersList);

                    // Control the start button
                    Data.LobbyLink.Dispatcher.Invoke(new Action(delegate()
                    {
                        Data.LobbyLink.Go();
                    }));
                    Data.LobbyLink.Dispatcher.Invoke(new Action(delegate()
                    {
                        Data.LobbyLink.CheckPing();
                    }));
                }
            }
        }