SocketException:重新连接后重置连接

时间:2013-09-24 16:59:13

标签: java sockets exception

如果我首先启动服务器,然后客户端一切正常,但是当我首先启动客户端然后启动服务器(确保客户端能够在svr崩溃然后再次联机时连接)客户端确实连接到服务器,但在2,3秒后抛出SocketException:Connection reset。我不知道是什么导致它,如果有人可以帮我解决这个问题,我会非常感激。

处理客户端的服务器代码:

public ServerHandler(Socket socket){
    try{
        pw = new PrintWriter(socket.getOutputStream());
        writerHolder[userCounter] = pw;

        InputStreamReader in = new          InputStreamReader(socket.getInputStream());
        reader = new BufferedReader(in);


        userCounter++;// Increment the number of people connected

    }catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

连接到服务器的客户端代码:

    private  void startConnection()
{
    try
    {
        sock = new Socket("192.168.1.5", 5000);
        InputStreamReader input = new InputStreamReader(sock.getInputStream());
        reader = new BufferedReader(input);
        pw = new PrintWriter(sock.getOutputStream());
        JOptionPane.showMessageDialog(null, "Connected to the server!");

    }catch(IOException ex)
    {
        //timer.reconnectTimer(20);
        ex.printStackTrace();
    }
}

堆栈跟踪:

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 homeControl.ServerHandler.run(ServerHandler.java:52)
at java.lang.Thread.run(Unknown Source)

1 个答案:

答案 0 :(得分:1)

“连接重置”通常表示远程端关闭其插槽的一侧而不读取您发送的数据。确保在关闭套接字之前读取发送给您的数据。