服务端
package com.atguigu.nio.qunliao;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Set;
public class QServer {
private ServerSocketChannel listenChannel;
private Selector selector;
private static final int PORT = 6667;
public QServer() {
try {
selector = Selector.open();
listenChannel = ServerSocketChannel.open();
listenChannel.bind(new InetSocketAddress(PORT));
listenChannel.configureBlocking(false);
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
public void listen() {
System.out.println("监听线程: " + Thread.currentThread().getName());
try {
while (true) {
int conunt = selector.select();
if (conunt > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
selectionKeys.stream().forEach(key -> {
if (key.isAcceptable()) {
try {
SocketChannel socketChannel = listenChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println(socketChannel.getRemoteAddress() + "上线");
} catch (IOException e) {
e.printStackTrace();
}
}
if (key.isReadable()) {
readData(key);
}
selectionKeys.clear();
});
}else {
System.out.println("等待");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void readData(SelectionKey selectionKey) {
SocketChannel channel = null;
try {
channel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int count = channel.read(buffer);
if (count > 0) {
String msg = new String(buffer.array());
System.out.println("客户端 :" + msg);
snedInfo(msg, channel);
}
} catch (IOException e) {
try {
System.out.println(channel.getRemoteAddress() + "离线");
selectionKey.cancel();
channel.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
private void snedInfo(String msg, SocketChannel self) {
System.out.println("服务器转发消息");
selector.keys().stream().forEach(key -> {
Channel targetChannel = key.channel();
if (targetChannel instanceof SocketChannel && targetChannel != self) {
SocketChannel dest = (SocketChannel) targetChannel;
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
try {
dest.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) {
QServer qServer = new QServer();
qServer.listen();
}
}
客户端
package com.atguigu.nio.qunliao;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
import java.util.Set;
public class QClient {
private final String HOST = "127.0.0.1";
private final int PORT = 6667;
private SocketChannel socketChannel;
private Selector selector;
private String userName;
public QClient() throws IOException {
selector = selector.open();
socketChannel = socketChannel.open(new InetSocketAddress(HOST,PORT));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
userName = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(userName + "is ok ....");
}
private void sendMsg(String info){
info = userName + "说:"+info;
try{
socketChannel.write(ByteBuffer.wrap(info.getBytes()));
}catch (IOException e){
}
}
public void ReadServerMsg(){
try {
int readChannels = selector.select();
if (readChannels > 0){
Set<SelectionKey> selectionKeys = selector.selectedKeys();
selectionKeys.stream().forEach(key -> {
if (key.isReadable()){
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer allocate = ByteBuffer.allocate(1024);
try {
sc.read(allocate);
String msg = new String(allocate.array());
System.out.println(msg.trim());
} catch (IOException e) {
e.printStackTrace();
}
}else {
System.out.println("没有可用通道");
}
});
selectionKeys.clear();
}
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
QClient qClient = new QClient();
new Thread(() -> {
while (true){
qClient.ReadServerMsg();
try {
Thread.currentThread().sleep(3000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String s = scanner.nextLine();
qClient.sendMsg(s);
}
}
}