1

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

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,这表明连接不再建立。

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

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

4

2 回答 2

1

根据我的经验,Dispose 关闭底层流。

因此,您关闭 Dispose 上的连接。

于 2013-07-24T13:20:31.267 回答
0

我在按照 GetStream() 的 MS 文档中的步骤复制的这段代码遇到了同样的问题: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()语句执行时,服务端报告客户端关闭了连接。检查流的属性我可以看到流拥有套接字。所以,当它关闭时,它也必须关闭它的套接字。怎么会???

于 2019-06-07T05:08:53.663 回答