服务端
package nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
public class Server {
private static int SERVER_PORT = 9999;
private Selector selector;
private ServerSocketChannel serverSocketChannel;
public Server() throws Exception {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(SERVER_PORT));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public static void main(String[] args) throws Exception {
Server server = new Server();
server.listen();
}
public void listen() {
try {
while (true) {
int count = selector.select(1000);
if (count > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println(socketChannel.getRemoteAddress() + " 上线了...");
}
if (key.isReadable()) {
readClient(key);
}
iterator.remove();
}
} else {
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public void readClient(SelectionKey key) throws Exception {
SelectableChannel channel = null;
SocketChannel socketChannel = null;
try {
channel = key.channel();
socketChannel = (SocketChannel) channel;
ByteBuffer buffer = ByteBuffer.allocate(1024);
int count = socketChannel.read(buffer);
if (count > 0) {
String msg = new String(buffer.array());
System.out.println("from client: " + msg.trim());
sendMsgToOtherClient(msg, socketChannel);
}
} catch (IOException e) {
try {
System.out.println(socketChannel.getRemoteAddress() + " 离线了...");
key.cancel();
socketChannel.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void sendMsgToOtherClient(String msg, SocketChannel channel) throws Exception {
System.out.println("服务端开始转发客户端的消息... " + msg.trim());
Set<SelectionKey> keys = selector.keys();
for (SelectionKey selectionKey : keys) {
Channel targetChannel = selectionKey.channel();
if (targetChannel instanceof SocketChannel && channel != targetChannel) {
SocketChannel destChannel = (SocketChannel) targetChannel;
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
destChannel.write(buffer);
}
}
}
}
客户端
package nio;
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;
import java.util.Scanner;
import java.util.Set;
public class Client {
private static final String IP = "127.0.0.1";
private static final int SERVER_PORT = 9999;
private Selector selector;
private SocketChannel socketChannel;
private String username;
public Client() {
try {
selector = Selector.open();
socketChannel = SocketChannel.open(new InetSocketAddress(IP,SERVER_PORT));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
username = socketChannel.getLocalAddress().toString().substring(1);
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendInfo(String msg){
try {
String info = username + " 说 " + msg;
socketChannel.write(ByteBuffer.wrap(info.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void receiveInfo(){
try {
int count = selector.select();
if (count > 0){
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
if (selectionKey.isReadable()){
SocketChannel channel = (SocketChannel)selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
String msg = new String(buffer.array());
System.out.println("读取到服务器的数据是: "+msg.trim());
}
}
iterator.remove();
}else {
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
new Thread(()->{
while (true) {
client.receiveInfo();
}
}).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String msg = scanner.nextLine();
client.sendInfo(msg);
}
}
}