在 Java 里“网络断线重连”一般分 场景 来看:
下面按常见情况给你讲清楚做法和示例代码。
IOException / SocketExceptionpublic class ReconnectSocket {
private Socket socket;
private String host;
private int port;
public ReconnectSocket(String host, int port) {
this.host = host;
this.port = port;
}
public void connect() {
while (true) {
try {
socket = new Socket(host, port);
System.out.println("连接成功");
readData(socket);
break;
} catch (IOException e) {
System.out.println("连接断开,5秒后重连");
closeQuietly(socket);
sleep(5000);
}
}
}
private void readData(Socket socket) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println("收到:" + line);
}
}
private void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException ignored) {}
}
private void closeQuietly(Socket s) {
try { if (s != null) s.close(); } catch (IOException ignored) {}
}
public static void main(String[] args) {
new ReconnectSocket("127.0.0.1", 9000).connect();
}
}
✅ 优点:实现简单
❌ 缺点:阻塞线程
避免网络风暴:
int retry = 0;
while (true) {
try {
connect();
break;
} catch (IOException e) {
retry++;
long wait = Math.min(30000, (long) Math.pow(2, retry) * 1000);
Thread.sleep(wait);
}
}
OkHttpClient client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
int retry = 3;
while (retry-- > 0) {
try {
// 调用 HTTP
break;
} catch (IOException e) {
Thread.sleep(2000);
}
}
webSocket.onClosed(() -> reconnect());
webSocket.onFailure((e) -> reconnect());
void reconnect() {
scheduler.schedule(this::connect, 3, TimeUnit.SECONDS);
}
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelInactive(ChannelHandlerContext ctx) {
ctx.channel().eventLoop().schedule(
() -> bootstrap.connect(), 5, TimeUnit.SECONDS);
}
});
}
});
❌ 重连不关旧连接 → 文件句柄泄露
❌ 无限重连无上限 → 系统崩
❌ 主线程阻塞 → 用线程 / 线程池
❌ 不判断“主动断开”
我可以直接给你一套可复制的完整重连方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。