2017-04-14 104 views
0

我正在學習Java編程的Socket編程。我得到java.net.SocketException: Connection reset獲取錯誤「java.net.SocketException:連接重置」

客戶端代碼

package com.socket; 

    import java.io.OutputStreamWriter; 
    import java.io.PrintWriter; 
    import java.net.Socket; 

    public class ClientSock { 

     public static void main(String[] args) throws Exception { 

      Socket skt = new Socket("localhost", 8888);  
      String str = "Hello Server"; 
      OutputStreamWriter osw = new OutputStreamWriter(skt.getOutputStream()); 

      PrintWriter out = new PrintWriter(osw); 
      osw.write(str); 
      osw.flush();   
     } 
    } 

//Server Side Code: 

    package com.socket; 

    import java.io.BufferedReader; 
    import java.io.InputStreamReader; 
    import java.net.ServerSocket; 
    import java.net.Socket; 

    public class ServerSock { 

     public static void main(String[] args) throws Exception { 

      System.out.println("Server is Started"); 
      ServerSocket ss = new ServerSocket(8888); 

      Socket s = ss.accept(); 

      BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); 
      String str = br.readLine(); 

      System.out.println("Client Says : " + str);   
     } 
    } 

這裏被運行後,客戶端代碼我的控制檯,我得到異常連接復位,在那裏我做錯了嗎?

Server is Started 
Exception in thread "main" java.net.SocketException: Connection reset 
    at java.net.SocketInputStream.read(Unknown Source) 
    at java.net.SocketInputStream.read(Unknown Source) 
    at sun.nio.cs.StreamDecoder.readBytes(Unknown Source) 
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source) 
    at sun.nio.cs.StreamDecoder.read(Unknown Source) 
    at java.io.InputStreamReader.read(Unknown Source) 
    at java.io.BufferedReader.fill(Unknown Source) 
    at java.io.BufferedReader.readLine(Unknown Source) 
    at java.io.BufferedReader.readLine(Unknown Source) 
    at com.socket.ServerSock.main(ServerSock.java:19) 
+0

可能重複[什麼導致我的java.net.SocketException:連接重置?](http://stackoverflow.com/questions/585599/whats-causing-my-java-net-socketexception-connection-reset) – halfer

+0

[很多其他潛在的重複](https://stackoverflow.com/search?q=java.net.SocketException%3A+Connection+reset)。 – halfer

回答

1

「異常在線程‘主’java.net.SocketException異常:連接復位」當對手不調用關閉()被強制終止發生錯誤。

添加此行ClientSock

skt.close(); 

,我建議這個太ServerSock。

ss.close(); 

java.io.Closeable的實現對象必須調用close()。

+0

skt.close將刪除該異常,但不會刪除該異常的根本原因。可以有多個SocektException的現金 –

+0

是的,異常消失了! 我關閉了Socket和ServerSocket。 謝謝@Seminmin Gwon和Vineet Kasat。 –

0

您在「Hello Server」中忘記了「\ n」。
閱讀器無法獲得全部內容並拋出此異常。

相關問題