重复使用后,袜子显示不一致/不可能的结果

时间:2010-02-14 11:54:40

标签: c# .net sockets tcp

嘿所有,我试图确定一些服务器的状态随着时间的推移。 这是我的代码:

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.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);

        }


    }

当我运行此代码时,它显示24.15.169.211是第一次运行,然后在后续测试中恢复为无此服务器。为什么呢?

2 个答案:

答案 0 :(得分:2)

因为您正在尝试连接已连接的套接字。打印例外,你会看到出了什么问题。将catch子句改为

}catch (Exception ex) {
   Console.WriteLine(ex);
}

答案 1 :(得分:0)

这是使用TcpClient而不是原始套接字的略微修改版本:

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);
}