views:

16

answers:

0

I've written a simple chat program to experiment with some basic tcp/socket concepts. For some reason I've found that when I close my writer stream (which I am getting from the TcpClient.GetStream() function) it will send one final null message to my server. To top it all off it doesn't do this if I send one final message over the stream right before closing it. I can't seem to figure out why it would do this when the stream is empty, as opposed to after I've sent another message. Relevant code follows:

    public void Disconnect(string reason)
    {
        SendMessage(reason); // If I comment this line out the issue presents itself

        // Close all open streams/connections
        connected = false;
        swServerStream.Close(); // The null message is sent on this line
        tcpServer.Close();
    }

    public void SendMessage(String msg)
    {
        if (msg.Length >= 1)
        {
            if (connected)
            {
                lock (swServerStream)
                {
                    swServerStream.WriteLine(msg);
                }
            }
            else
            {
                WriteToUI(msg);
            }
        }
    }