客户端代码:
public class NIOClient {
public static void main(String[] args) throws IOException {
try {
SocketChannel socketChannel=SocketChannel.open();
socketChannel.configureBlocking(false);
Selector selector=Selector.open();
//监听客户端是否发起连接
socketChannel.register(selector, SelectionKey.OP_CONNECT);
socketChannel.connect(new InetSocketAddress("127.0.0.1",8899));
while (true){
selector.select();
Set<SelectionKey> selectionKeys=selector.selectedKeys();
for (SelectionKey selectionKey:selectionKeys){
if (selectionKey.isConnectable()){
SocketChannel client= (SocketChannel) selectionKey.channel();
if (client.isConnectionPending()){
client.finishConnect();
ByteBuffer writeBuffer=ByteBuffer.allocate(1024);
writeBuffer.put((LocalDateTime.now()+"连接成功").getBytes());
writeBuffer.flip();
client.write(writeBuffer);
ExecutorService executorService= Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
executorService.submit(()->{
while(true){
try{
writeBuffer.clear();
InputStreamReader input=new InputStreamReader(System.in);
BufferedReader bufferedReader=new BufferedReader(input);
String message=bufferedReader.readLine();
writeBuffer.put(message.getBytes());
writeBuffer.flip();
client.write(writeBuffer);
}
catch (Exception e){
e.printStackTrace();
}
}
});
}
client.register(selector,SelectionKey.OP_READ);
}else if (selectionKey.isReadable()){
SocketChannel client= (SocketChannel) selectionKey.channel();
ByteBuffer readBuffer=ByteBuffer.allocate(1024);
int count=client.read(readBuffer);
if (count>0){
String receiveMessage=new String(readBuffer.array(),0,count);
System.out.println(receiveMessage);
}
}
}
selectionKeys.clear();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
服务端代码:
public class NIOServer {
private static Map<String, SocketChannel> clientMap=new HashMap<>();
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(8899));
Selector selector=Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true){
try {
selector.select();
Set<SelectionKey> selectionKeys=selector.selectedKeys();
selectionKeys.forEach(selectionKey -> {
final SocketChannel client;
try {
if (selectionKey.isAcceptable()){
ServerSocketChannel serverSocketChannel1= (ServerSocketChannel) selectionKey.channel();
client=serverSocketChannel1.accept();
client.configureBlocking(false);
client.register(selector,SelectionKey.OP_READ);
String key="["+ UUID.randomUUID().toString()+"]";
clientMap.put(key,client);
}
else if(selectionKey.isReadable()){
client= (SocketChannel) selectionKey.channel();
ByteBuffer readBuffer=ByteBuffer.allocate(1024);
int count=client.read(readBuffer);
if (count>0){
readBuffer.flip();
Charset charset=Charset.forName("utf-8");
String reciveString=String.valueOf(charset.decode(readBuffer).array());
System.out.println(client+":"+reciveString);
String senderKey=null;
for (Map.Entry<String,SocketChannel> entry : clientMap.entrySet()){
if (client == entry.getValue()){
senderKey=entry.getKey();
break;
}
}
for (Map.Entry<String,SocketChannel> entry : clientMap.entrySet()){
SocketChannel socketChannel=entry.getValue();
ByteBuffer writeBuffer=ByteBuffer.allocate(1024);
writeBuffer.put((senderKey+":"+reciveString).getBytes());
writeBuffer.flip();
socketChannel.write(writeBuffer);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
});
//将key清空,相当于Itetor一次性remove
selectionKeys.clear();
}
catch (Exception e){
e.printStackTrace();
}
}
}
}