private void PingServer(ServerPinger pinger) { string error = ""; ServerPingData ping = pinger.PingServer(Data.IP, Data.Port, out error); Ping = ping; //If no error if (error == string.Empty) { //Set the controls with the recieved data Stats.Text = ping.Online + "/" + ping.MaxOnline; Motd.Text = ping.Description; Stats.TextColor = onlineColor; } else { //Error text Stats.Text = "X"; Stats.TextColor = offlineColor; Motd.Text = error; } Stats.Left = (ClientWidth - (int)Manager.Skin.Fonts["Default14"].Resource.MeasureString(Stats.Text).X) - 4 - 32; }
public ServerPingData PingServer(string host, int port, out string error) { ServerPingData pingData = new ServerPingData(); error = string.Empty; //Attempt to contact the server try { using (TcpClient client = new TcpClient()) { IAsyncResult ar = client.BeginConnect(host, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(Common.GlobalSettings.ConnectTimeout), false)) { client.Close(); error = "Offline (Connection Timeout)"; pingData.Error = true; return pingData; } client.EndConnect(ar); } finally { wh.Close(); } //Send a single message notifying the server we would like it's stats (0 is the ping request ID) data = new byte[1] { 0x00 }; //Get a client stream for reading and writing stream = client.GetStream(); //Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); int size = (stream.ReadByte() << 8) + stream.ReadByte(); Debug.WriteLine("ServerPinger Sent: " + data.ToString()); //Buffer to store the response bytes. data = new byte[size]; //Read the first batch of the TcpServer response bytes int bytes = stream.Read(data, 0, data.Length); using (MemoryStream ms = new MemoryStream(data)) { using (StreamReader reader = new StreamReader(ms)) { pingData.Online = (int)byte.Parse(reader.ReadLine()); pingData.MaxOnline = (int)byte.Parse(reader.ReadLine()); pingData.Description = reader.ReadLine(); } } client.Close(); } } catch (Exception e) { error = e.Message; pingData.Error = true; Debug.WriteLine(e.ToString()); if (e is SocketException) { //Provide some better error messages int id = (e as SocketException).ErrorCode; if (id == 10061) //No connection could be made because the target machine actively refused it error = "Offline (Target Online, Server Not Accessible)"; else if (id == 10060) //A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond error = "Offline (Connection Timeout)"; } } finally { if (client != null) client.Close(); } return pingData; }
/// <summary> /// Listens for ping requests, and sends back statistics /// </summary> private void Listen() { try { server = new TcpListener(IPAddress.Any, port); //Create a TcpListener to listen for requests server.Start(); //Start listening for client requests. byte[] bytes = new byte[1]; //Single byte buffer for reading data (should not exceed 1 byte) //Enter the listening loop. while (true) { client = server.AcceptTcpClient(); //Wait and accept requests stream = client.GetStream(); //Get a stream object for reading and writing int i; //Loop to receive all the data sent by the client while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { Debug.WriteLine(String.Format("PingListener: Data Received: {0}", bytes.ToString())); //If ping request recieved, send back the data (0 is the ping packet id) if ((byte)bytes[0] == 0x00) { Debug.WriteLine("PingListener: Data validated, query request recieved."); //Get server stats to send back ServerPingData pingData = Server.NetManager.GetQuery(); //Write the data to a steam and send using (MemoryStream ms = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(ms)) { writer.WriteLine((byte)pingData.Online); writer.WriteLine((byte)pingData.MaxOnline); writer.WriteLine(pingData.Description); } byte[] msg = ms.ToArray(); //(stream.ReadByte() << 8) + stream.ReadByte(); if (msg.Length > 65535) { throw new OverflowException("Please make your description smaller"); } // Writes the size of the message, up to 65535 stream.WriteByte((byte)(msg.Length >> 8)); stream.WriteByte((byte)(msg.Length % 255)); stream.Write(msg, 0, msg.Length); } } } // Shutdown and end connection client.Close(); } } catch (Exception e) { Log.WriteLine(LogType.Error, "PingListener Error: \"{0}\"", e.Message); } finally { server.Stop(); this.Start(); } }
public ServerPingData PingServer(string host, int port, out string error) { ServerPingData pingData = new ServerPingData(); error = string.Empty; //Attempt to contact the server try { using (TcpClient client = new TcpClient()) { IAsyncResult ar = client.BeginConnect(host, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(Common.GlobalSettings.ConnectTimeout), false)) { client.Close(); error = "Offline (Connection Timeout)"; pingData.Error = true; return(pingData); } client.EndConnect(ar); } finally { wh.Close(); } //Send a single message notifying the server we would like it's stats (0 is the ping request ID) data = new byte[1] { 0x00 }; //Get a client stream for reading and writing stream = client.GetStream(); //Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); int size = (stream.ReadByte() << 8) + stream.ReadByte(); Debug.WriteLine("ServerPinger Sent: " + data.ToString()); //Buffer to store the response bytes. data = new byte[size]; //Read the first batch of the TcpServer response bytes int bytes = stream.Read(data, 0, data.Length); using (MemoryStream ms = new MemoryStream(data)) { using (StreamReader reader = new StreamReader(ms)) { pingData.Online = (int)byte.Parse(reader.ReadLine()); pingData.MaxOnline = (int)byte.Parse(reader.ReadLine()); pingData.Description = reader.ReadLine(); } } client.Close(); } } catch (Exception e) { error = e.Message; pingData.Error = true; Debug.WriteLine(e.ToString()); if (e is SocketException) { //Provide some better error messages int id = (e as SocketException).ErrorCode; if (id == 10061) //No connection could be made because the target machine actively refused it { error = "Offline (Target Online, Server Not Accessible)"; } else if (id == 10060) //A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond { error = "Offline (Connection Timeout)"; } } } finally { if (client != null) { client.Close(); } } return(pingData); }