2017-04-23 63 views
-1

我想寫一個tcp客戶端和服務器程序。服務器的工作就好了,它通常打開插座,但是當我運行客戶端程序,我得到以下錯誤:爲什麼我會得到「java.net.SocketExcpecption:連接重置」?

Exception in thread "main" java.net.SocketException: Connection reset 
    at java.net.SocketInputStream.read(Unknown Source) 
    at java.net.SocketInputStream.read(Unknown Source) 
    at server.Client.main(Client.java:22) 

誰能告訴我怎麼解決?在此先感謝

這裏是我的客戶端代碼

public class Client { 

private final static String serverIP = "192.168.56.1"; 
private final static int serverPort = 50000; 
private final static String fileOutput ="D:\\Julian\\Kancolle.7z"; 

public static void main(String args[]) throws UnknownHostException, IOException { 
    Socket sock = new Socket(serverIP, serverPort); 
    byte[] byte_arr = new byte[1024]; 
    InputStream is = sock.getInputStream(); 
    FileOutputStream fos = new FileOutputStream(fileOutput); 
    BufferedOutputStream bos = new BufferedOutputStream(fos); 
    int bytesRead = is.read(byte_arr, 0, byte_arr.length); 
    bos.write(byte_arr, 0, bytesRead); 
    bos.close(); 
    sock.close(); 
    } 
} 

和服務器代碼

public class Server implements Runnable { 

private final static int serverPort = 50000;      // reserves port 
private final static String fileInput = "D:\\Julian\\Kancolle";  // destination 

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

    int bytesRead; // buffer variable 

    ServerSocket servsock = new ServerSocket(serverPort); 
    File myFile = new File(fileInput); 
    while (true) { 
     Socket sock = servsock.accept(); 

     InputStream in = sock.getInputStream(); 
     OutputStream output = new FileOutputStream(myFile); 
     byte[] buffer = new byte[1024]; // buffer 

     while((bytesRead = in.read(buffer)) != -1) 
     { 
      output.write(buffer, 0, bytesRead);; 
     } 
     output.close(); 
     servsock.close(); 
    } 
} 

public static void start(){ 
    Server upd = new Server(); 
    Thread tupd = new Thread(upd); 
    tupd.start(); 
} 

@Override 
public void run() { 

} 
} 
+0

此代碼不會產生此異常,除非您終止了服務器進程。 – EJP

回答

0

這沒有任何意義。雙方都從插座讀取數據並複製到FileOutputStream。沒有人通過套接字發送任何東西。所以真正發生的是第一次連接之後的互讀死鎖。

您還錯誤地關閉accept()循環內的ServerSocket。因此,當您嘗試接受第二個連接時,服務器會收到一個未公開的SocketException: socket closed退出,操作系統將關閉泄露的接受套接字,並根據平臺將FIN或重置傳播給對等設備。

+0

讓它工作,謝謝! – zennok

相關問題