server
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class GroupServer {
private Selector selector;
private ServerSocketChannel serverSocketChannel;
private static final int PORT = 6667;
public GroupServer() {
try {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (Exception e) {
e.printStackTrace();
}
}
public void listen() {
System.out.println("开始监听");
try {
while (true) {
int count = selector.select(2000);
if (count > 0) {
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isAcceptable()) {
SocketChannel sc = serverSocketChannel.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
System.out.println("用户 " + sc.getRemoteAddress() + " 上线了");
}
if (key.isReadable()) {
readData(key);
}
}
keyIterator.remove();
}else {
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public void sendInfoToOtherClients(String msg, SocketChannel self) {
try {
for (SelectionKey key : selector.keys()) {
Channel channel = key.channel();
if (channel instanceof SocketChannel && channel != self) {
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
((SocketChannel) channel).write(buffer);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
private void readData(SelectionKey key) {
SocketChannel socketChannel = null;
try {
socketChannel = (SocketChannel) key.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());
sendInfoToOtherClients(msg, socketChannel);
}
} catch (Exception e) {
try {
System.out.println(socketChannel.getRemoteAddress() + " 离线了");
key.cancel();
socketChannel.close();
} catch (IOException e2) {
e2.printStackTrace();
}
} finally {
}
}
public static void main(String[] args) {
try {
GroupServer groupServer = new GroupServer();
groupServer.listen();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
client
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;
public class GroupClient {
private static final String HOST = "127.0.0.1";
private static final int PORT = 6667;
private Selector selector;
private String userName;
private SocketChannel socketChannel;
public GroupClient() throws Exception {
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 + " client is ok");
}
public void sendInfo(String info) {
info = userName + " 说:" + info;
try {
socketChannel.write(ByteBuffer.wrap(info.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}
public void readInfo() {
try {
int readChannels = selector.select(2000);
if (readChannels > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
sc.read(buffer);
String msg = new String(buffer.array());
System.out.println(msg.trim());
}
iterator.remove();
}
}else {
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static void main(String[] args) throws Exception {
GroupClient client = new GroupClient();
new Thread(()->{
while (true) {
client.readInfo();
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
client.sendInfo(s);
}
}
}