所以我正在编写一个简单的客户端-服务器应用程序。它应该发送一个数据包,然后等待接收一个数据包,而不是发送一个等等......问题是,它收到了第一个数据包,但是当我TcpListener
在第二次迭代中开始时,它给了我这个错误:
无法建立连接,因为目标机器主动拒绝它 127.0.0.1:13
private void listenForConnections()
{
bool prejelPaket = false;
listener = new TcpListener(IPAddress, port);
listener.Start();
while (!packetReceived)
{
try
{
client = listener.AcceptTcpClient();
listener.Stop();
networkStream = client.GetStream();
byte[] message = new byte[1024];
networkStream.Read(message, 0, message.Length);
networkStream.Close();
string strMessage = Encoding.UTF8.GetString(message);
packetReceived= true;
MessageBox.Show("received message: " + strMessage);
client.Close();
}
catch (Exception ee)
{
thListen.Join();
}
}
}
private void sendPacket(object pClient)
{
string message = "test message;
try
{
client = (TcpClient)pClient;
client.Connect(IPAddress, port);
networkStream = client.GetStream();
byte[] strMessage = Encoding.UTF8.GetBytes(message);
networkStream.Write(strMessage, 0, strMessage.Length);
networkStream.Close();
client.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}