服务端
package com.jhj.nio.groupchat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class GroupChatServer {
private Selector selector;
private ServerSocketChannel listenChannel;
private static final int PROT = 6667;
public GroupChatServer() {
try {
selector = Selector.open();
listenChannel=ServerSocketChannel.open();
listenChannel.socket().bind(new InetSocketAddress(PROT));
listenChannel.configureBlocking(false);
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException 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();
if (key.isAcceptable()) {
SocketChannel sc = listenChannel.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
System.out.println(sc.getRemoteAddress() + "上线");
}
if (key.isReadable()) {
readDate(key);
}
iterator.remove();
}
} else {
System.out.println("等待...");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
private void readDate(SelectionKey key) {
SocketChannel channel = null;
try {
channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int count = channel.read(byteBuffer);
if (count > 0) {
String s = new String(byteBuffer.array());
System.out.println("from客户端:" + s);
sendInfoToOtherClients(s, channel);
}
} catch (IOException e) {
try {
System.out.println(channel.getRemoteAddress() + "离线了....");
key.cancel();
channel.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void sendInfoToOtherClients(String s, SocketChannel socketChannel) throws IOException {
System.out.println("服务器转发消息中");
for (SelectionKey key : selector.keys()) {
Channel channel = key.channel();
if (channel instanceof SocketChannel && channel != socketChannel) {
SocketChannel channel1 = (SocketChannel) channel;
ByteBuffer wrap = ByteBuffer.wrap(s.getBytes());
channel1.write(wrap);
}
}
}
public static void main(String[] args) {
GroupChatServer groupChatServer = new GroupChatServer();
groupChatServer.listen();
}
}
客户端
package com.jhj.nio.groupchat;
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;
public class GroupChatClient {
private final String HOST="127.0.0.1";
private final int PROT=6667;
private Selector selector;
private SocketChannel socketChannel;
private String username;
public GroupChatClient() throws IOException {
selector = Selector.open();
socketChannel=SocketChannel.open(new InetSocketAddress(HOST,PROT));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
username = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(username+"is ok");
}
public void sendInfo(String info){
info=username+"说:"+info;
try {
socketChannel.write(ByteBuffer.wrap(info.getBytes()));
}catch (IOException 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 next = iterator.next();
if (next.isReadable()){
SocketChannel channel = (SocketChannel) next.channel();
ByteBuffer allocate = ByteBuffer.allocate(1024);
channel.read(allocate);
String s = new String(allocate.array());
System.out.println(s.trim());
}
iterator.remove();
}
}else {
}
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
GroupChatClient groupChatClient = new GroupChatClient();
new Thread(){
public void run(){
while (true){
groupChatClient.readInfo();
try{
Thread.currentThread().sleep(3000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}.start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String s=scanner.nextLine();
groupChatClient.sendInfo(s);
}
}
}
作者声明
如有问题,欢迎指正!