我用于同步消息交换的客户端类:
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 为假。
有什么想法可以解决这个问题吗?