NIO编程中,socket服务端重启后,客户端报java.nio.channels.ClosedChannelException

这个问题是客户端和服务器的管道关闭了。导致这个问题的原因是服务端程序重启或者关闭重开导致的。

解决这个问题的方法是在捕获异常的时候,对报错位置进行try-catch

。如果报错,先把原来的网络管道socketchannel关闭,重新创建管道并连接服务端,注意不是创建客户端对象而是管道

代码如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Java NIO 来实现服务端的开发,同时使用普通的 Socket 来实现客户端的开发。下面是一个简单的示例: 服务端代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; public class NIOServer { public static void main(String[] args) throws IOException { // 创建 ServerSocketChannel 对象 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); // 绑定监听端口 serverSocketChannel.bind(new InetSocketAddress(8888)); // 设置为非阻塞模式 serverSocketChannel.configureBlocking(false); while (true) { // 接受客户端连接 SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel != null) { // 收到客户端连接 System.out.println("接收到客户端连接:" + socketChannel.getRemoteAddress()); // 创建缓冲区 ByteBuffer buffer = ByteBuffer.allocate(1024); // 读取客户端发送的数据 int bytesRead = socketChannel.read(buffer); if (bytesRead > 0) { // 切换缓冲区为读模式 buffer.flip(); // 解码数据 String message = StandardCharsets.UTF_8.decode(buffer).toString(); System.out.println("收到客户端消息:" + message); // 回复客户端 buffer.clear(); buffer.put("Hello, Client!".getBytes(StandardCharsets.UTF_8)); buffer.flip(); socketChannel.write(buffer); } } } } } ``` 客户端代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; public class SocketClient { public static void main(String[] args) throws IOException { // 创建 Socket 对象 Socket socket = new Socket(); // 连接服务器 socket.connect(new InetSocketAddress("localhost", 8888)); // 发送消息到服务器 String message = "Hello, Server!"; socket.getOutputStream().write(message.getBytes(StandardCharsets.UTF_8)); // 接收服务器回复的消息 byte[] buffer = new byte[1024]; int bytesRead = socket.getInputStream().read(buffer); if (bytesRead > 0) { String reply = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8); System.out.println("收到服务器消息:" + reply); } // 关闭连接 socket.close(); } } ``` 在上面的示例服务端使用 `ServerSocketChannel` 来监听客户端连接,并使用 `SocketChannel` 来读取客户端发送的数据,并回复消息。客户端使用普通的 `Socket` 来连接服务端,并发送消息到服务端,并接收服务端回复的消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值