這是從客戶端接收值的函數。但問題是我只收到一次。無論多少次發送一些數據,MainWindows上的標籤只會被更改一次。通過套接字接收/發送數據不完全工作,只接收一次值
我在這裏做錯了什麼?
private void HandleClientComm(object client)
{
tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
break;
}
if (bytesRead == 0)
{
break;
}
if (String.IsNullOrWhiteSpace(data))
{
ASCIIEncoding encoder = new ASCIIEncoding();
data = encoder.GetString(message, 0, bytesRead);
MainWindow.Change(data);
tcpClient.Close();
}
tcpClient.Close();
}
在客戶端我有這下面的例子:
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1", 8001);
Console.WriteLine("Connected");
while (true)
{
Console.Write("Enter the string to be transmitted : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
stm.Flush();
Console.WriteLine("Sent.....");
}
tcpclnt.Close();
Console.Read();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
公正的快速例子,所以當我輸入的字符串名稱,價值變動第一次,但是當我進入第二次或者如果我退出客戶端程序並重新輸入任何內容,則標籤內容的值等於第一次發送的值。
它沒有工作,我現在檢查你的圖書館。謝謝。 – moenad 2013-02-19 19:11:08
到您網站的鏈接實際上並不是問題的答案,而只是爲了宣傳您的圖書館而設計的。預計堆棧溢出的答案將直接與被問到的問題相關。 – 2013-02-19 21:10:56
@AndrewBarber - 恕我直言,我的答案的第一部分直接回答了這個問題。第二部分讓OP知道我的經驗是更好的解決方案。如果我不包括第二部分,請告知。 – MarcF 2013-02-19 21:18:51