TcpClient主机名挂起

时间:2012-12-02 05:56:15

标签: c# tcpclient hang hostname

我在使用TcpClient通过StreamWriter写入的流发送数据时遇到问题。

    private void sendMessage(string[] hostlist, string message)
    {
        foreach (string host in hostlist)
        {
            try
            {
                messageClient = new TcpClient(host, 24300);
                StreamWriter writer = new StreamWriter(messageClient.GetStream());
                writer.Write(message);
                writer.Flush();
            }
            catch (Exception)
            {
                MessageBox.Show("Error 1\n" +
                                "This may be due to two things:\n" +
                                "1. The hostname is invalid.\n" +
                                "2. The destination computer is not online.",
                                "Error Sending Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

    }

问题行是初始化messageClient的地方。如果我使用IP地址,则根本没有挂起,即时发送和接收消息。但是,如果我使用诸如“lappy”(我的笔记本电脑的名称)之类的主机名,程序将完全挂起6秒,然后发送消息。每次尝试使用主机名发送消息时都会发生这种情况。我有什么问题吗?如果您需要使用主机名而不是IP地址,是否有不同的实现?

感谢。

1 个答案:

答案 0 :(得分:0)

我发现的最佳解决方案是自己解析主机名并使用其中的地址。

例如,

IPHostEntry hostlist = Dns.Resolve(hostname[0]);
IPAddress address = hostlist.AddressList[0];

IPAddress地址是我最终发送邮件的地址。

由于我的程序计划在任何时候都没有使用IP地址的用户界面,所以只要将消息发送到正确的计算机,现在无论程序发送到哪个IP都无关紧要。