public class GroupChatServer {
private Selector selector;
private ServerSocketChannel listenChannel;
private static final int PORT = 6666;
public GroupChatServer() {
try {
selector = Selector.open();
listenChannel = ServerSocketChannel.open();
listenChannel.socket().bind(new InetSocketAddress(PORT));
listenChannel.configureBlocking(false);
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (Exception e) {
e.printStackTrace();
}
}
public void listen() {
try {
while (true) {
int count = selector.select();
if (count > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
listenHandler(key);
iterator.remove();
}
} else {
System.out.println("当前没事件要处理,等待中……");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void listenHandler(SelectionKey key) {
SocketChannel sc = null;
try {
if (key != null && key.isAcceptable()) {
sc = listenChannel.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
System.out.println(sc.getRemoteAddress().toString().substring(1) + "上线了");
}
if (key != null && key.isReadable()) {
sc = (SocketChannel) key.channel();
sc.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(1024);
int count = sc.read(buffer);
if (count > 0) {
String msg = new String(buffer.array());
System.out.println("from client " + msg);
sendMsgToClient(msg, sc);
}
}
} catch (IOException e) {
try {
System.out.println(sc.getRemoteAddress().toString().substring(1) + "离线了");
key.cancel();
sc.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public void sendMsgToClient(String msg, SocketChannel self) throws IOException {
System.out.println("服务器转发消息中");
for (SelectionKey key : selector.keys()) {
Channel channel = key.channel();
if (channel instanceof SocketChannel && channel != self) {
SocketChannel targetChannel = (SocketChannel) channel;
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
targetChannel.write(buffer);
}
}
}
public static void main(String[] args) {
GroupChatServer server = new GroupChatServer();
server.listen();
}
}
public class GroupChatClient {
private final String HOST = "127.0.0.1";
private final int PORT = 6666;
private Selector selector;
private SocketChannel socketChannel;
private String username;
public GroupChatClient() {
try {
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");
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMsgToServer(String msg) {
msg = username + ":" + msg;
try {
socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}
public void acceptMsgFromServer() {
try {
int readChannel = selector.select();
if (readChannel > 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();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
GroupChatClient client = new GroupChatClient();
new Thread() {
public void run() {
while (true) {
client.acceptMsgFromServer();
try {TimeUnit.SECONDS.sleep(3); } catch (Exception e) { e.printStackTrace();}
}
}
}.start();
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String msg = scanner.nextLine();
client.sendMsgToServer(msg);
}
}
}