0

I'm having a problem with using a TcpClient to send data over a stream written to by a 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);
            }

        }

    }

The problem line is where messageClient is initialized. If I use an IP address, there is no hang at all, the message is instantly sent and received. However, if I use a hostname such as "lappy" (name of my laptop) the program completely hangs for exactly 6 seconds, then sends the message. This happens every time you attempt to send a message using a hostname. Is there something I'm doing wrong here? Is there a different implementation if you need to use hostnames rather than IP addresses?

Thanks.

lmcintyre
  • 98
  • 7

1 Answers1

0

The best solution I've found is to resolve the hostname yourself and use the address in that.

For example,

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

The IPAddress address is the address that I'll end up sending the message to.

Since the planning of my program ended up not having the user interface with the IP addresses at any point, it now does not matter which IP the program sends to, as long as the message gets sent to the correct computer.

lmcintyre
  • 98
  • 7