예제 #1
0
        // Deserialize a JSON stream to a User object.
        public static Gamers ReadClient(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 Gamers();
                var    ms  = new MemoryStream(Encoding.UTF8.GetBytes(returnData));
                var    ser = new DataContractJsonSerializer(deserializedUser.GetType());
                deserializedUser = ser.ReadObject(ms) as Gamers;
                ms.Close();
                return(deserializedUser);
            }
            catch
            {
                return(null);
            }
        }
예제 #2
0
        // Create a User object and serialize it to a JSON stream.
        public static byte[] WriteClient(Gamers 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(Gamers));
                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
파일: Client.cs 프로젝트: endrewsmith/TMC
        // For each message its own stream
        public void SendMessagesThread(int typeMassage, Gamers gamerSender)

        {
            Client send       = new Client();
            Thread sendThread = new Thread(delegate() { send.SendMessages(typeMassage, gamerSender); });

            sendThread.Start();
        }
예제 #4
0
파일: Client.cs 프로젝트: endrewsmith/TMC
        // For sending messages
        public void SendMessages(int typeMassage, Gamers gamerSender)
        {
            try
            {
                gamerSender.Type   = typeMassage;
                gamerSender.Number = Data.MyNamber;
                _tcpStream.Write(Json.WriteClient(gamerSender), 0, Json.WriteClient(gamerSender).Length);
                _tcpStream.Flush();
            }
            catch

            { }
        }
예제 #5
0
        // Add the client to the lists
        public static void AddUser(Gamers gamer)

        {
            Set printData         = new Set();
            Get closingOrNotLobby = new Get();

            // Number which I will assign to the new player
            int gamerNumber;

            // Add to the list of players and assign a number

            Data.GamersList.gamer.Add(gamer);
            gamerNumber = Data.GamersList.gamer.Count - 1;
            Data.GamersList.gamer[gamerNumber].Number = gamerNumber;

            // The player becomes the last in the lobby
            Data.LastNumber = gamerNumber;

            // Add tables from another stream to the collection
            Data.Inf.Dispatcher.Invoke(new Action(delegate()
            {
                Data.gamerList.Add(Data.GamersList.gamer[gamerNumber]);
            }));


            // Showing who joined
            printData.SetMassageAddLeave(true, Data.LastNumber);

            // Send a new list to all players
            Data.GamersList.Type = 0;
            SendAllThread(Data.GamersList);

            // Close the Ready button until ping appears
            Data.LobbyLink.Dispatcher.Invoke(new Action(delegate()
            {
                Data.LobbyLink.CheckPing();
                Data.LobbyLink.FlashWin();
            }));

            // Close the lobby or not
            closingOrNotLobby.GetClosingLobby();

            // Control the start button
            Data.LobbyLink.Dispatcher.Invoke(new Action(delegate()
            {
                Data.LobbyLink.Go();
            }));
        }
예제 #6
0
파일: Client.cs 프로젝트: endrewsmith/TMC
        // Initialization
        public void InitializeConnection(string ip, int port)

        {
            _tcpServer = null;
            Set printData = new Set();

            try
            {
                TryConectToRandomPortIteration(10);
            }

            // If it didn’t succeed in contacting the specified port,
            // the program tries random ports (10 iterations)
            catch (Exception ex)
            {
                if (!TryConectToRandomPortIteration(5))
                {
                    // If it didn’t turn out to find the port, we tell the player about it and exit
                    MainWin.Message("TCP error", "Did not manage to pick up tcp port for a connection");

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

                    return;
                }
            }

            try
            {
                Connected = true;

                _ipHost = IPAddress.Parse(ip);
                IAsyncResult result = _tcpServer.BeginConnect(_ipHost, port, null, null);

                // Set timeout for connection
                bool success = result.AsyncWaitHandle.WaitOne(2000, true);

                if (!_tcpServer.Connected)
                {
                    CloseConnection("Connection error", "You cannot join this lobby. Some problem with the TCP port");
                    return;
                }
            }

            // If it didn’t succeed in connecting, show a message
            catch (Exception ex)
            {
                CloseConnection("Connection error", "You cannot join this lobby. Some problem with the TCP");
                return;
            }

            _tcpStream = _tcpServer.GetStream();

            // Create an object for serialization:
            Gamers Gamer = new Gamers();

            if (!Data.JoinToServer)
            {
                Gamer.Key = "yes";
            }
            Gamer.Type    = 0;
            Gamer.Name    = Data.SettingCh.St.Name;
            Gamer.Status  = 0;
            Gamer.Car     = Data.SettingCh.St.Car;
            Gamer.Team    = Data.SettingCh.St.Team;
            Gamer.Message = ip;

            if (Data.JoinToServer)
            {
                if (Data.webList[Data.LobbyNumber].PasswordInp == null)
                {
                    Gamer.Password = "";
                }
                else
                {
                    Gamer.Password = Data.webList[Data.LobbyNumber].PasswordInp;
                }
            }

            // Sending to client
            _tcpStream.Write(Json.WriteClient(Gamer), 0, Json.WriteClient(Gamer).Length);
            _tcpStream.Flush();


            // Open thread reciaving messages
            _thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
            _thrMessaging.Start();
        }
예제 #7
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 { }
            }
        }