2011-07-20 36 views
1

我是網絡新手,當我試圖運行MyClient.java時,我收到EOFException。Java:網絡中的EOFException

MyServer.java

public class MyServer { 
    public static void main(String[] args) { 
     ServerSocket serverSocket = null; 
     try { 
      serverSocket = new ServerSocket(4321); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     while(true) { 
      try { 
       Socket socket = serverSocket.accept(); 
       OutputStream os =socket.getOutputStream(); 
       OutputStreamWriter osw = new OutputStreamWriter(os); 
       BufferedWriter bw = new BufferedWriter(osw); 
       bw.write("Hello networking"); 

       bw.close(); 
       socket.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

MyClient.java

public class MyClient { 
    public static void main(String[] args) { 
     Socket socket = null; 
     try { 
      socket = new Socket("127.0.0.1", 4321); 
      InputStream is = socket.getInputStream(); 
      DataInputStream dis = new DataInputStream(is); 
      System.out.println(dis.readUTF()); 

      dis.close(); 
      socket.close(); 
     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (ConnectException e) { 
      System.err.println("Could not connect"); 
     } catch (UTFDataFormatException e) { 
      System.err.println("if the bytes do not represent a valid modified UTF-8 encoding of a string"); 
     } catch (EOFException e) { 
      System.err.println("if this input stream reaches the end before reading all the bytes"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我得到如果此輸入流達到讀取所有字節的錯誤和錯誤之前結束似乎來自dis.readUTF()調用。

有人能幫我理解我錯過了什麼嗎?我試圖讀取服務器在連接時寫入客戶端的內容,即Hello networking

謝謝。

回答

1

問題出在您的服務器代碼 如果您想使用DataInputStream讀取它,則應該使用DataOutputStream.writeUTF(String str)寫入套接字。

+0

它工作:)。謝謝。 – skip