Sock shows inconsistent/impossible results after repeat use
Hey all, I am trying to determine the status of some servers over the course of time. Here is my code:
static void Main(string[] args)
{
byte[] readstream = new byte[100];
byte[] sendstream = Encoding.ASCII.GetBytes("PLAYER_JOINED");
string[] IPs = new string[] { "24.15.169.211", "69.198.255.121", "219.79.244.225" };
string[] Name = new string[10];
string[] Port = new string[10];
int timeout = 5000;
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.ReceiveTimeout = timeout;
while (true)
{
int i = 0;
foreach (string str in IPs)
{
IPAddress address = IPAddress.Parse(str);
IPEndPoint CheckingServer = new IPEndPoint(address, 8190);
try
{
s.Connect(CheckingServer);
s.Send(sendstream);
s开发者_Python百科.Receive(readstream);
Console.WriteLine(Encoding.ASCII.GetString(readstream));
Console.WriteLine("{0}: Server Up", IPs[i]);
}
catch
{
Console.WriteLine("{0}: NO SUCH SERVER", IPs[i]);
}
i++;
}
Thread.Sleep(1000);
}
}
When I run this code, it shows that 24.15.169.211 is up THE FIRST TIME IT RUNS THROUGH, but then reverts to no such server in subsequent tests. Why?
Because you're trying to connect an already connected socket. Print the exception and you'll see what goes wrong. Change your catch clause to
}catch (Exception ex) {
Console.WriteLine(ex);
}
Here's a slightly modified version using TcpClient instead of raw sockets:
var ipsToCheck = new[] { "24.15.169.211", "69.198.255.121", "219.79.244.225" };
while (true)
{
foreach (var ip in ipsToCheck)
{
using (var tcpClient = new TcpClient(AddressFamily.InterNetwork))
{
tcpClient.ReceiveTimeout = 5000;
try
{
tcpClient.Connect(IPAddress.Parse(ip), 8190);
using (var stream = tcpClient.GetStream())
{
var writer = new StreamWriter(stream);
var reader = new StreamReader(stream);
writer.Write("PLAYER_JOINED");
var buffer = new char[100];
reader.Read(buffer, 0, buffer.Length);
Console.WriteLine(buffer);
Console.WriteLine("{0}: Server Up", ip);
}
}
catch (Exception ex)
{
Console.WriteLine("Error connecting to {0}: {1}", ip, ex.Message);
}
}
}
Thread.Sleep(1000);
}
精彩评论