我的目标是创建一个保持连接的TcpClient,允许将消息发送到服务器,以及使用定时监视器在特定空闲频率期间向服务器发送特殊消息。在被难倒之前没有做得太远。
使用当前代码,使用控制台测试程序应用程序发送的第一条消息收到罚款,但在发送另一条消息时会抛出异常,并显示消息“非连接套接字上不允许进行操作。”
我尝试删除stream.Dispose()行,它会在第二次尝试期间挂起在stream.Read(...)上。我还尝试将NetworkStream流作为类的成员并在构造函数中将其设置为client.GetStream(),并在第二次尝试期间挂起在stream.Read(...)上。
public class TcpClientTest
{
private TcpClient client = new TcpClient();
private string hostName;
private int port;
public TcpClientTest(string hostName, int port)
{
this.hostName = hostName;
this.port = port;
client.Connect(hostName, port);
}
public byte[] SendMessage(string name, string message)
{
if (client == null) throw new Exception("Client connection has not been established");
Person person = new Person();
person.Name = name; person.Message = message;
byte[] messageBytes = (System.Text.Encoding.Unicode.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(person)));
const int bytesize = 1024 * 1024;
try
{
NetworkStream stream = client.GetStream();
if (stream != null)
{
stream.Write(messageBytes, 0, messageBytes.Length); // Write the bytes
messageBytes = new byte[bytesize]; // Clear the message
// Receive the stream of bytes
stream.Read(messageBytes, 0, messageBytes.Length);
}
// Clean up
stream.Flush();
stream.Dispose();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return messageBytes; // Return response
}
}
// In console tester app
static void Main(string[] args)
{
TcpClientTest client = new TcpClientTest("127.0.0.1", 1234);
string exit = "2";
do
{
if (exit == "1") client.SendMessage("TEST", "TEST");
Console.WriteLine("1 Send Message 2 Exit");
exit = Console.ReadLine();
} while (exit != "2");
}