2
響應,我有以下一段代碼來聽一個端口是55000.無限循環從服務器
static void TcpEchoServer(string _servPort)
{
int servPort = Convert.ToInt32(_servPort);
TcpListener listener = null;
try
{
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
}
catch (SocketException sec)
{
Console.WriteLine(sec.ErrorCode + ": " + sec.Message);
Environment.Exit(sec.ErrorCode);
}
byte[] rcvBuffer = new byte[BUFSIZE];
int bytesRcvd;
for (; ;)
{
TcpClient client = null;
NetworkStream netStream = null;
try
{
// Get client connection and stream
client = listener.AcceptTcpClient();
netStream = client.GetStream();
Console.Write("Handling client - ");
// Receive until client closes connection, indicated by 0 return value
int totalBytesEchoed = 0;
bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length);
while (bytesRcvd > 0)
{
netStream.Write(rcvBuffer, 0, bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);
// Close stream and socket
netStream.Close();
client.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
netStream.Close();
}
}
}
一旦我打開啓動服務器,我telnet我的命令提示符併發送消息,但不斷得到一個循環響應我的客戶端,但沒有響應我的服務器。任何人發現我的問題?我不能。我在Mac機器上的VMWare上開發Window 7 VS2010 C#,並從Mac終端遠程登錄。
[EDIT - 代碼答案]
我簡單地分配字節接收變量的while循環中,所以不會循環,只要它完成。謝謝你指出這個問題。以下是我的解決方案代碼:
while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
{
netStream.Write(rcvBuffer, 0, bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
+1您指出了問題。用我的解決方案查看編輯的問題我在while循環的條件中分配變量。到目前爲止它的工作。 – KMC 2012-03-03 01:01:15