为什么我得到" java.net.SocketExcpecption:连接重置"?

时间:2017-04-23 02:48:09

标签: java sockets tcp network-programming java-io

我正在尝试编写tcp客户端和服务器程序。服务器运行正常,它正常打开套接字,但是当我运行客户端程序时,我收到以下错误:

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() {

}
}

1 个答案:

答案 0 :(得分:0)

这没有任何意义。双方正在从套接字读取并复制到FileOutputStream。没有人通过套接字发送任何东西。所以真正应该发生的是第一次连接后的互读死锁。

您也错误地关闭了ServerSocket循环中的accept()。因此,当您尝试接受第二个连接时,您的服务器将获得未公开的SocketException: socket closed,退出,操作系统将关闭泄漏的已接受套接字,并将FIN或重置传播给对等方,具体取决于平台。