我正在做一個客戶端 - 服務器應用程式,服務器將檢查何時有資料可用 (TcpClient.Available > 0) 讀取,但是當它運行 SslStream.Read 時,即使我知道我需要讀取多少位元組,它仍然將 TcpClient.Available 設定回 0 并保留已讀取的位元組......我的代碼未讀取,因為條件 (TcpClient.Available > 0) 將是假的,因此服務器不會對額外的位元組做任何事情,直到客戶端發送更多的位元組,這是不想要的,服務器應該盡快處理客戶端發送的所有位元組。這是一些代碼:
static void main()
{
TcpClient tcpClient = listener.AcceptTcpClient();
SslStream s = new SslStream(tcpClient.GetStream(), false);
//authenticate etc ...
while (true)
{
if (tcpClient.Available > 0) // now this condition is false until
// the client send more bytes
// which is not wanted
work(tcpClient);
}
}
static void work(TcpClient c)
{
//client sent 50 bytes
byte[] data = new byte[10];
s.Read(data, 0, 10); // I know this is not guaranteed to read 10 bytes
//so I have a while loop to read until it receives all the byes, this line is just for example
// do something with the 10 bytes I read, back to the while loop
}
我的“作業”實際上創建了一個新執行緒來完成作業并鎖定該客戶端直到作業完成,以便該客戶端在作業完成之前不會呼叫作業
由于我知道運行“作業”需要多少位元組,因此我只讀取該位元組數并解鎖客戶端,以便客戶端可以再次“作業”
當然還有其他客戶端也需要作業,這里我只展示一個來演示問題
uj5u.com熱心網友回復:
你通常不知道是多少位元組左從流中讀取。
但是您可以“在讀取時”從流中讀取,因為SslStream.Read回傳讀取的位元組數!
所以你的代碼變成了簡單的
while (s.Read(data, 0, 10) > 0)
{
// do something with the bytes you've read
}
這是人們處理流的一般方式 - 在閱讀時按塊閱讀它們。
您可以在我之前鏈接的檔案中的示例中看到它(還有更多!您應該明確地檢查它)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/376363.html
