2012-04-02 46 views
-2

我正在構建客戶端服務器應用程序,其中客戶端必須發送一些字節流,並且服務器根據從客戶端接收到的字節進行響應。我正在使用NetworkStream.WriteNetworkStream.Read方法發送和接收數據。客戶端能夠創建到服務器的TCP連接。在接受連接之後,服務器會執行NetworkStream.Read並等待來自客戶端的一些輸入。客戶使用NetworkStream.Write發送數據,也發送NetworkStream.Flush。但服務器永遠不會從Read中喚醒。無法讀取C#中的字節流

你們可以建議我這裏有什麼問題,或者如果你知道任何其他方法通過C#中的TCP連接發送字節流,請讓我知道。

謝謝!

+0

第一:請發佈您使用的實際代碼 - 第二:嘗試關閉客戶端寫入字節後的連接,因爲我的猜測是,您正在使用*流*不是正確的方式 – Carsten 2012-04-02 04:13:48

+1

我可以從代碼中可以看出,它很可能是由海王星發射的粒子干擾的。我強烈建議你用錫紙遮擋你的整個城市,以獲得更高質量的傳輸。 – 2012-04-02 04:18:17

+0

第一:我已經解釋了代碼..在這個問題中,我只關注2行,我的客戶端是Network.Write,我的服務器是Network.Read。 其次,我正在創建一個連接,並從我的客戶端進行寫入操作,然後執行Read操作以獲取服務器的響應。我在那裏僵持不下。 – user1296146 2012-04-02 04:45:06

回答

1

撇開Smart-ass的意見:即使你只對2行代碼感興趣,我敢打賭你的問題是在你的代碼中的其他地方。

使用發現的代碼的修改版本here,我構建了一個簡單的例子,在我的測試中起作用。

public static void Main() 
    { 
     TcpListener server = null; 
     try 
     { 
      // Set the TcpListener on port 13000. 
      Int32 port = 13000; 
      IPAddress localAddr = IPAddress.Parse("127.0.0.1"); 

      // TcpListener server = new TcpListener(port); 
      server = new TcpListener(localAddr, port); 

      // Start listening for client requests. 
      server.Start(); 

      // Buffer for reading data 
      Byte[] bytes = new Byte[256]; 

      Console.Write("Waiting for a connection... "); 

      // Perform a blocking call to accept requests. 
      // You could also user server.AcceptSocket() here. 
      TcpClient client = server.AcceptTcpClient(); 
      Console.WriteLine("Connected!"); 

      // Get a stream object for reading and writing 
      NetworkStream stream = client.GetStream(); 

      stream.Read(bytes, 0, bytes.Length); 
      Console.WriteLine(System.Text.Encoding.ASCII.GetString(bytes)); 
      // Shutdown and end connection 
      client.Close(); 
     } 
     catch (SocketException e) 
     { 
      Console.WriteLine("SocketException: {0}", e); 
     } 
     finally 
     { 
      // Stop listening for new clients. 
      server.Stop(); 
     } 


     Console.WriteLine("\nHit enter to continue..."); 
     Console.Read(); 
    } 

讀取調用將等待並返回時,我與另一程序1個字節的發送。我們需要看一些代碼來弄清楚爲什麼這個工作,而你的不工作。