// Listen and wait for messages public void ReceiveMessage() { receiver_server = null; Set printData = new Set(); int buffer_size = 256; bool firstMessLd = true; string time_now = ""; int real_ping; IPEndPoint LdIpPort = null; string message = ""; Get get_param = new Get(); // UDP port FROM FILE for listening from all IPs int portReciever = 0; if (Data.HostOrClient) { Int32.TryParse(Data.SettingCh.St.UdpPort, out portReciever); } else { Random randomUdpPort = new Random(); portReciever = randomUdpPort.Next(49152, 65535); } Data.UdpWorkRec = true; int num; try { receiver_server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint localIP = new IPEndPoint(IPAddress.Any, portReciever); receiver_server.Bind(localIP); } catch (Exception ex) { MainWin.Message("Udp port error", "Failed to determine UDP port, specify it in the settings yourself"); } string[] parts; string[] partr; // Buffer for received data byte[] data = new byte[buffer_size]; byte[] data_ = new byte[6]; // Client for mailing to ld (for mailing to other players) UdpClient sendToLd = new UdpClient(); // The address from which the data came EndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0); if (Data.HostOrClient) { num = 1; } else { num = 0; } try { int bytes; // UDP listening cycle starts immediately and works while there is a room // first listens to ping, then receives data from clients while (Data.UdpWorkRec == true) { try { // Get data _buffer = receiver_server.ReceiveFrom(data, buffer_size, SocketFlags.None, ref remoteIp); // } catch (Exception ex) { } if (data[0] == 's') { // Converted from bytes to string to parse message = Encoding.Unicode.GetString(data, 0, 6); parts = message.Split('s'); int number = 0; Int32.TryParse(parts[1], out number); Array.Clear(data, 0, buffer_size); string message2 = "r" + Data.MyNamber + "r"; data_ = Encoding.Unicode.GetBytes(message2); try { { receiver_server.SendTo(data_, remoteIp); } } catch (Exception ex) { } // When ping arrives, the host always updates its data if (Data.HostOrClient) { if (Data.LastNumber != 0) { Data.GamersList.gamer[number].Udp = remoteIp as IPEndPoint; // If there is ping with everyone if (get_param.GetReadyPing()) { Data.ChatStatic.Dispatcher.Invoke(new Action(delegate() { Data.GamersList.Type = 7; Host.SendAllThread(Data.GamersList); })); // After the exchange, discard the last player before another Data.LastNumber = 0; } } } } else if (data[0] == 'r') { // Get the first ping point time_now = DateTime.Now.ToString("ss.fff"); // Converted from bytes to string to parse message = Encoding.Unicode.GetString(data, 0, _buffer); partr = message.Split('r'); int number = 0; Int32.TryParse(partr[1], out number); time_now = time_now.Replace(".", ""); stop_point[number] = 0; Int32.TryParse(time_now, out stop_point[number]); real_ping = stop_point[number] - start_point[number]; try { if (Data.GamersList.gamer[number] != null) { if (real_ping >= 1000) { double _realPing = real_ping / 1000; Data.GamersList.gamer[number].GPing = _realPing.ToString("N2"); } else if (real_ping >= 10000) { double _realPing = real_ping / 1000; Data.GamersList.gamer[number].GPing = _realPing.ToString("N1"); } else if (real_ping >= 0) { Data.GamersList.gamer[number].GPing = real_ping.ToString(); } } // If the host then I check for ping always if (Data.HostOrClient) { Data.LobbyLink.Dispatcher.Invoke(new Action(delegate() { Data.LobbyLink.CheckPing(); })); } } catch { } Array.Clear(data, 0, buffer_size); } else if (data[0] == 'u') { Set messag = new Set(); messag.SetText("UDP port is open"); } else if (data[0] < 3) { data[0] += 5; // If the first message, then determine the address if (firstMessLd == true) { // We receive data about LD and we will send them from players LdIpPort = remoteIp as IPEndPoint; firstMessLd = false; } // Mailing to all players except yourself for (int i = num; i < Data.GamersList.gamer.Count; i++) { // Send a package to everyone except myself if (Data.MyNamber != i) { try { receiver_server.SendTo(data, Data.GamersList.gamer[i].Udp); } catch (Exception ex) { } } } // Clean the buffer Array.Clear(data, 0, buffer_size); } else { data[0] -= 5; if (LdIpPort != null) { sendToLd.Send(data, data.Length, LdIpPort); } // Clean the buffer Array.Clear(data, 0, buffer_size); } } // Exit the loop and close the listening socket if (receiver_server != null) { receiver_server.Close(); } // Close the send socket on ld if (sendToLd != null) { sendToLd.Close(); } } catch (Exception ex) { } }
// Get the lobby list and fill in the table public string GetLobbyList() { Set printData = new Set(); string serveranswer = ""; string[] line; string[] pars; int numRoom = 0; List <Lobby> LobbySortList = new List <Lobby>(); try { // Send a request to the server serveranswer = SendToServer("cmd=get"); if (serveranswer != null && serveranswer != "err" && serveranswer != "") { int _lastCount = Data.webList.Count; // Share the response by session line = serveranswer.Split('&'); try { Data.Inf.Dispatcher.Invoke(new Action(delegate() { // Clear the list before filling it LobbySortList.Clear(); })); } catch { return("err"); } foreach (var part in line) { if (part != "" && part != null) { // In order not to count from zero, enter the counter from 1 numRoom++; // Divide sessions by parameters pars = part.Split('|'); Get getType = new Get(); // Use this function of receiving through the separator ":" string type = getType.GetIpAndPort(pars[6], 0); string mod = getType.GetIpAndPort(pars[6], 1); // Get a password or not, and IdTime string _pass = getType.GetIpAndPort(pars[3], 0); int _id = 0; Int32.TryParse(getType.GetIpAndPort(pars[3], 1), out _id); string openClose = getType.GetIpAndPort(pars[9], 0); string comment = getType.GetIpAndPort(pars[9], 1); int count = 0; Int32.TryParse(pars[4], out count); try { if (count > 0) { Data.LobbyList.Dispatcher.Invoke(new Action(delegate() { LobbySortList.Add(new Lobby() { Name = pars[0], Host = LobbyPlayers(pars[5])[0], Players = LobbyPlayers(pars[5]), Map = pars[7], Type = type, Password = _pass, IdTime = _id, ModOrigin = mod, OpenCloseIngame = openClose, Comment = comment, Score = pars[8], IP = pars[1], Port = pars[2], Count = GetMaxCountGamers(type, count), CountOne = pars[4] }); })); } } catch { return("err"); } } else { // Erases information Set inf = new Set(); inf.SetInfo(0); } } // Start sorting the list, the first sorting by creation date is always there var sortedList = LobbySortList.OrderBy(x => x.IdTime).ToList(); Data.Inf.Dispatcher.Invoke(new Action(delegate() { // Build a list by numbers for (int i = 0; i < sortedList.Count; i++) { sortedList[i].Number = i + 1; } // Before distillation into the table, I clean it Data.webList.Clear(); if (!Data.SettingCh.St.Sort1 && !Data.SettingCh.St.Sort2 && !Data.SettingCh.St.Sort3 && !Data.SettingCh.St.Sort4) { for (int i = 0; i < sortedList.Count; i++) { Data.webList.Add(sortedList[i]); } } else if (Data.SettingCh.St.Sort1) { var sortedListMod = sortedList.OrderByDescending(x => x.OpenCloseIngame).ThenBy(x => x.Password).ThenBy(x => x.ModOrigin).ToList(); for (int i = 0; i < sortedList.Count; i++) { Data.webList.Add(sortedListMod[i]); } } else if (Data.SettingCh.St.Sort2) { var sortedListOrig = sortedList.OrderByDescending(x => x.OpenCloseIngame).ThenBy(x => x.Password).ThenByDescending(x => x.ModOrigin).ToList(); for (int i = 0; i < sortedList.Count; i++) { Data.webList.Add(sortedListOrig[i]); } } else if (Data.SettingCh.St.Sort3) { var sortedListMap = sortedList.OrderByDescending(x => x.OpenCloseIngame).ThenBy(x => x.Password).ThenBy(x => x.Map).ToList(); for (int i = 0; i < sortedList.Count; i++) { Data.webList.Add(sortedListMap[i]); } } if (Data.SettingCh.St.Sort4) { var sortedListType = sortedList.OrderByDescending(x => x.OpenCloseIngame).ThenBy(x => x.Password).ThenBy(x => x.Type).ToList(); for (int i = 0; i < sortedList.Count; i++) { Data.webList.Add(sortedListType[i]); } } })); return("ok"); } else { Data.Inf.Dispatcher.Invoke(new Action(delegate() { // Clear the list LobbySortList.Clear(); Data.webList.Clear(); // Erases information Set inf = new Set(); if (serveranswer == null) { inf.SetSomeInfo("Server is not responding. Check if the server is specified correctly in the settings \r\n"); } if (serveranswer == "") { inf.SetSomeInfo("No lobby found \r\n"); } if (serveranswer == "err") { inf.SetSomeInfo("Server is not responding. Check if the server is specified correctly in the settings \r\n"); } })); return("ok"); } } catch { if (Data.FollowToGetLobby) { Data.Inf.Dispatcher.Invoke(new Action(delegate() { // Clear the list LobbySortList.Clear(); Data.webList.Clear(); // Erases information Set inf = new Set(); inf.SetInfo(0); inf.SetSomeInfo("Server is not responding. Check if the server is specified correctly in the settings \r\n"); })); } return("err"); } }
// 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(); })); } } }