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

本文关键字:TcpClient 失败 getStream 建立 | 更新日期: 2023-09-27 18:24:55

用于同步消息交换的My Client类:

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

问题是我没有主动关闭任何地方的连接。如果我把连接。Connect(主机,端口)在调用getStream()之前,它会失败,除非套接字仍然连接,即使是连接。Connected为false。

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

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

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

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

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