所以我寫了一個簡單的客戶端 - 服務器應用程序。它應該發送一個數據包,然後等待接收數據包,然後發送一個數據包......問題是,它接收到第一個數據包,但是當我在第二次迭代中啓動TcpListener
時,它給了我這個錯誤:TcpListener不會確認連接
No connection could be made because the target machine actively refused it 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());
}
}
謝謝,這對我有很大幫助,現在效果很好。乾杯。 – Kajzer 2013-05-03 10:08:56