2012-01-11 66 views
1

我正在用C#客戶套接字和Java服務器套接字創建一個套接字連接。 當我從客戶端套接字發送數據時,服務器套接字正在正確接收該數據。 但是當我試圖從服務器套接字發送數據回到客戶端套接字時,它在客戶端接收數據時被掛起。從Java服務器套接字接收C#客戶端套接字中的數據時出錯

客戶端代碼(在C#.NET)

  clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); 

      string hostName = System.Net.Dns.GetHostName(); 
      System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(hostName); 
      System.Net.IPAddress[] ipAddresses = hostEntry.AddressList; 
      System.Net.IPEndPoint remoteEP = 
       new System.Net.IPEndPoint(ipAddresses[ipAddresses.Length - 1], port); 
      clientSocket.Connect(remoteEP); 
      string sendData = inputFilePath; 
        byte[] byteDataSend = System.Text.Encoding.ASCII.GetBytes(sendData); 
        clientSocket.Send(byteDataSend); 

        int receivedBufferSize = clientSocket.ReceiveBufferSize; 
        byte[] recivedData = new Byte[receivedBufferSize]; 
        int receivedDataLength = clientSocket.Receive(recivedData); 
        string stringData = Encoding.ASCII.GetString(recivedData, 0, receivedDataLength); 
        textFilePath = stringData; 
        Console.Write(stringData); 
        clientSocket.Close(); 

服務器套接字代碼(在Java)

  Socket connection = server.accept(); 
      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
      fileName = in.readLine(); 
      convertedFile =runConverter.convertDocumet(fileName); 
      byte[] sendingData = convertedFile.getBytes("US-ASCII"); 
      DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); 
      dos.write(sendingData, 0, sendingData.length); 

告訴我是什麼問題? 請幫忙...

回答

0

這種c#代碼的通常問題是同步接收。
我總是建議進行異步讀取,如this answer

我不確定這是問題的根源,但是如果您通過一些日誌記錄來實現異步接收,那麼很可能會解決您的問題或使其更明顯問題是。

對同步接收的掛起確實表明Java不會將數據發送到c#正在偵聽的同一個套接字,因此仔細檢查這些端點也是一個好主意。

希望有幫助!

相關問題