2012-05-31 115 views
2

我從java套接字開始,並有奇怪的[缺少]輸出。下面是我的源套接字方法:Java客戶端/服務器插座

客戶端源代碼:

public void loginToServer(String host, String usnm) { 
    try { 
     Socket testClient = new Socket(host,1042); 
     System.out.println ("Connected to host at " + host); 
     logString = ("CONNECTED: " + host); 
     outGoing = new PrintWriter(testClient.getOutputStream(), true); 
     outGoing.print("Hello from " + testClient.getLocalSocketAddress()); 
     InputStream inFromServer = testClient.getInputStream(); 
     DataInputStream in = new DataInputStream(inFromServer); 
     System.out.println("Server says " + in.readLine()); 
     testClient.close(); 
    } 
    catch (Exception e) { 
     System.err.println ("Error connecting to host at " + host + ":1042.\n Reason: " + e); 
     logString = ("CONNECT FAILED: " + host + ":1042: " + e); 
    } 
    printLog(logString); 
    // send server usnm and os.name [System.getProperty(os.name)] ? 
} 

而且服務器代碼:

public void runServer() { 
     try{ 
      server = new ServerSocket(1042); 
     } 
     catch (IOException e) { 
      printLog("LISTEN FAIL on 1042: " + e); 
      System.err.println("Could not listen on port 1042."); 
      System.exit(-1); 
     } 
     try{ 
      client = server.accept(); 
     } 
     catch (IOException e) { 
      printLog("ACCEPT FAIL on 1042: " + e); 
      System.err.println("Accept failed: 1042"); 
      System.exit(-1); 
     } 
     try{ 
      inComing = new BufferedReader(new InputStreamReader(client.getInputStream())); 
      outGoing = new PrintWriter(client.getOutputStream(), true); 
     } 
     catch (IOException e) { 
      printLog("READ FAIL on 1042: " + e); 
      System.err.println("Read failed"); 
      System.exit(-1); 
     } 
     while(true){ 
      try{ 
       clientData = inComing.readLine(); 
       //processingUnit(clientData, client); 
       outGoing.print("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!"); 
      } 
      catch (IOException e) { 
      printLog("READ FAIL on 1042: " + e); 
       System.out.println("Read failed"); 
       System.exit(-1); 
      } 
     } 
    } 

而且客戶給了輸出僅僅是Connected to host at localhost

發生了什麼事?

回答

2

您正在閱讀線路,但您並未發送線路。將print()更改爲println()readLine()將永遠阻止等待換行符。它將在流結束時返回null,即當對端關閉連接時,但你不檢查這一點,所以你無限循環。

+0

修好了! :D歡呼一束 – gossfunkel

2

您正在編寫文本和閱讀二進制文件。由於您的輸出和輸入不匹配,因此很有可能在此情況下掛起。

我建議你使用帶有writeUTF/readUTF的二進制文件或帶有println/readLine的文本。

BTW:readUTF讀取兩個字節以確定要讀取的數據的長度。由於前兩個字節是ASCII文本,因此在返回之前可能需要等待大約16,000個字符。

+0

感謝一束,我永遠不會猜到。每種類型都適用於哪些情況? – gossfunkel

+0

文字適合發送人類可讀的單詞和數字。二進制數據可以高效準確地發送數據。 –

+0

這似乎並不是問題。糾正了這一點,似乎服務器沒有執行while循環中的代碼?它正在進入循環,但沒有嘗試或捕捉... – gossfunkel