gpt4 book ai didi

java - 套接字异常 : Connection reset after reconnect

转载 作者:行者123 更新时间:2023-12-01 14:04:49 26 4
gpt4 key购买 nike

如果我先启动服务器,然后启动客户端,一切都会正常,但是当我先启动客户端,然后启动服务器时(确保客户端能够在 svr 崩溃时连接,然后再次上线),客户端确实连接到服务器,但 2.3 秒后它抛出 SocketException:连接重置。我不知道是什么原因造成的,如果有人能帮助我解决这个问题,我将非常感激。

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

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)

最佳答案

“连接重置”通常意味着远程端关闭了套接字的一侧,而没有读取您发送的数据。确保在关闭套接字之前读取发送给您的数据。

关于java - 套接字异常 : Connection reset after reconnect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18987705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com