解决Java断开连接异常(DisconnectedException)的方法
解决Java断开连接异常(DisconnectedException)的方法
在使用Java进行网络编程时,有时候会遇到连接断开的异常,其中一种常见的异常就是DisconnectedException。这个异常通常出现在网络连接不稳定或者网络资源被释放的情况下。为了避免这个异常的发生,我们可以采取一些措施来解决。
以下是几个解决DisconnectedException异常的方法:
// 客户端发送心跳包 Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { outputStream.write("ping".getBytes()); } catch (IOException e) { e.printStackTrace(); } } }, 0, 5000); // 服务器端接收心跳包 Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { byte[] buffer = new byte[1024]; int length = inputStream.read(buffer); if (length == -1) { throw new DisconnectedException("Connection disconnected."); } String message = new String(buffer, 0, length); if (message.equals("ping")) { outputStream.write("pong".getBytes()); } } catch (IOException e) { e.printStackTrace(); } } }, 0, 5000);登录后复制