若客户端强制关闭,服务器会报“java.io.IOException: 远程主机强迫关闭了一个现有的连接。”,并且服务器会在报错后停止运行,错误的意思就是客户端关闭了,但是服务器还在从这个套接字通道读取数据,便抛出IOException,导致这种情况出现的原因就是,客户端异常关闭后,服务器的选择器会获取到与客户端套接字对应的套接字通道SelectionKey,并且这个key的兴趣是OP_READ,执行从这个通道读取数据时,客户端已套接字已关闭,所以会出现“java.io.IOException: 远程主机强迫关闭了一个现有的连接”的错误。解决这种问题也很简单,就是服务器在读取数据时,若发生异常,则取消当前key并关闭通道,如下代码:

//获取此key对应的套接字通道
SocketChannel channel = (SocketChannel) key.channel();
//创建一个大小为1024k的缓存区
ByteBuffer buffer = ByteBuffer.allocate(1024);
StringBuffer sb = new StringBuffer();
//将通道的数据读到缓存区
int count = 0;
try{
count = channel.read(buffer);
}catch(IOException e){
key.cancel();
channel.socket().close();
channel.close();
return;
}

因在catch中取消了key,readMsg返回后,run方法继续往下走,之前的代码会报“java.nio.channels.CancelledKeyException”错误,所以需要判断当前key是否有效,

之前的代码:

//若此key的通道的行为是"读"
if (key.isReadable()) {
readMsg(key);
}
//若次key的通道的行为是"写"
if (key.isWritable()) {
writeMsg(key);
}

修复后的代码:

//若此key的通道的行为是"读"
if (key.isValid() && key.isReadable()) {
readMsg(key);
}
//若次key的通道的行为是"写"
if (key.isValid() && key.isWritable()) {
writeMsg(key);
}

这样改良之后的聊天室服务端,客户端异常强制关闭后,服务器便会妥善处理了,也不会报错,更不会停止运行。改良之后还算比较稳定运行的。

异常代码:

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
/**
* Created by zhubo on 2018/1/16.
*/
public class NIOServer {
private Selector selector;
public void initServer(int port) throws Exception{
//获得一个ServerSocket通道
ServerSocketChannel serverChannel = ServerSocketChannel.open();
//设置通道为非阻塞
serverChannel.configureBlocking(false);
// 该通道对于serverSocket绑定到port端口
serverChannel.socket().bind(new InetSocketAddress(port));
// 获得一选择器
this.selector = Selector.open();
//将通道管理器和该通道绑定,并未该通道注册selectionKey.OP_ACCEPT事件
//注册该事件后,当事件到达的时候,selector.select()会返回,
// 如果事件没有到达selector.select()会一直阻塞
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void listen() throws Exception{
System.out.println("start server ...");
// 轮训访问seletor
while(true){
//当注册事件到达时,方法返回,否则该方法会一直阻塞
selector.select();
// 获得selector中选中项的地带器,选中项为注册事件
Iterator iterator = this.selector.selectedKeys().iterator();
if(iterator.hasNext()){
SelectionKey key = iterator.next();
//删除已选的key 以防止重复处理
iterator.remove();
//客户端请求链接事件
if(key.isValid() && key.isAcceptable()){
System.out.println("acceptable....");
ServerSocketChannel server = (ServerSocketChannel) key.channel();
//获取客户端链接的通道
SocketChannel channel = server.accept();
// 非阻塞模式
channel.configureBlocking(false);
//channel.write(ByteBuffer.wrap(new String("Hello Client").getBytes()));
// 在客户端链接成功后,为了可以连接到客户端的信息,需要给通道设置读的权限
channel.register(this.selector,SelectionKey.OP_READ);
}else if(key.isValid() && key.isReadable()){
read(key);
}
}
}
}
private void read(SelectionKey key) throws Exception {
SocketChannel channel = (SocketChannel)key.channel();
ByteBuffer buffer = ByteBuffer.allocate(100);
channel.read(buffer);
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("server receive from client : "+msg);
ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
channel.write(outBuffer);
//key.cancel();
//channel.close();
}
public static void main(String[] args) throws Exception{
NIOServer server = new NIOServer();
server.initServer(8989);
server.listen();
}
}
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
/**
* 
* Created by zhubo on 2018/1/16.
*/
public class NIOClient {
private Selector selector;
public void initClient(String ip, int port) throws IOException { // 获得一个Socket通道
SocketChannel channel = SocketChannel.open(); // 设置通道为非阻塞
channel.configureBlocking(false); // 获得一个通道管理器
this.selector = Selector.open(); // 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调
// 用channel.finishConnect();才能完成连接
channel.connect(new InetSocketAddress(ip, port));
// 将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。
channel.register(selector, SelectionKey.OP_CONNECT);
}
public void listen() throws Exception { // 轮询访问selector
while (true) {
// 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞,
// 这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时,
// selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的
selector.select(); // 获得selector中选中的项的迭代器
Iterator ite = this.selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next(); // 删除已选的key,以防重复处理
ite.remove(); // 连接事件发生
if (key.isConnectable()) {
System.out.println("Connectable ...");
SocketChannel channel = (SocketChannel) key.channel(); // 如果正在连接,则完成连接
if (channel.isConnectionPending()) {
channel.finishConnect();
} // 设置成非阻塞
channel.configureBlocking(false);
// 在这里可以给服务端发送信息哦
channel.write(ByteBuffer.wrap(new String("hello server!").getBytes()));
// 在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。
channel.register(this.selector, SelectionKey.OP_READ); // 获得了可读的事件
} else if (key.isReadable()) {
read(key);
}
}
}
}
private void read(SelectionKey key) throws Exception {
SocketChannel channel = (SocketChannel) key.channel();
// 穿件读取的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(100);
channel.read(buffer);
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("client receive msg from server:" + msg);
//key.cancel();
//channel.close();
//ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
//channel.write(outBuffer);
}
/**
* * // 启动客户端测试 * @throws IOException
* @throws Exception
*/
public static void main(String[] args) throws Exception {
NIOClient client = new NIOClient();
client.initClient("localhost", 8989);
client.listen();
}
}