TcpClient已建立,但TcpClient.getStream()失败

时间:2013-07-24 12:56:25

标签: c# tcp network-programming

我的同步消息交换客户端类:

public class AsClient
{
    private TcpClient connection;

    public AsClient(int serverPort, String ip)
    {
        connection = new TcpClient(ip, port);
    }

    public AsMessage sendMessage(AsMessage message)
    {
        System.Diagnostics.Debug.WriteLine("Connected: " + connection.Connected);
        NetworkStream ns = connection.GetStream();

        StreamReader reader = new StreamReader(ns);
        StreamWriter writer = new StreamWriter(ns);

        // Send Message:
        String msgToSendEncoded = message.encode();
        writer.WriteLine(msgToSendEncoded);
        writer.WriteLine("\n"); // each message is terminated by a paragraph
        writer.Flush();

        // Receive Message:
        String msgReceivedRaw = reader.ReadLine();
        AsMessage response = AsMessage.decode(msgReceivedRaw);

        reader.Dispose();
        writer.Dispose();

        ns.Close();

        return response;
    }
}

如果我调试此应用程序,发送的第一条消息和收到的响应工作得非常好,但是一旦我想发送第二条消息,TcpClient.getStream()就会失败,并显示InvalidOperationException,该条件表明连接未建立了。

问题是我没有在任何地方主动关闭连接。如果我在调用getStream()之前放入connection.Connect(host,port),它会失败,但套接字仍然连接,即使connection.Connected为false。

有什么想法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

根据我的经验,Dispose关闭基础流。

所以你关闭Dispose上的连接。

答案 1 :(得分:0)

我在这段代码中遇到了同样的问题,该代码复制遵循MS文档中关于GetStream()的步骤:https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.getstream?view=netframework-4.8

    public void Send(String message)
    {
        try
        {
            // Translate the passed message into ASCII and store it as a Byte array.
            Byte[] data = Encoding.ASCII.GetBytes(message);

            // Get a client stream for reading and writing.
            NetworkStream stream = Client.GetStream();

            stream.Write(data, 0, data.Length);

             stream.Close(); // this also closses the connection the server!
        }
        catch (Exception e)
        {
            LogException(e);
        }

    }

我们在服务器端看到的是: 1)建立连接。 2)消息永远不会到达。 3)执行stream.Close()语句时,服务器报告客户端关闭了连接。 检查流的属性,我可以看到流拥有套接字。因此,它关闭时也必须关闭其插座。怎么了???