客户端
public class NIOClient {
/**
* 1、连接服务器
* 2、发消息 收消息
*/
//定义属性
private final String host = "127.0.0.1"; //服务器ip
private final int port = 6667; //端口
private Selector selector;
private SocketChannel socketChannel;
private String username;
//构造器
public NIOClient(){
//完成初始化工作
try {
selector = selector.open();
//连接服务器
socketChannel = socketChannel.open(new InetSocketAddress(host,port));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
//得到username
username = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(username + " *** 客户端初始化完成");
} catch (IOException e) {
e.printStackTrace();
}
}
//发送消息
private void sendMsg(String msg){
msg = username + "说: " + msg;
try {
socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
}catch (Exception e){
e.printStackTrace();
}
}
//读取从服务器端回复的消息
private void readMsg(){
try {
int read = selector.select(1000);
if (read >0) {
//有可用通道
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
channel.read(byteBuffer);
String info = new String(byteBuffer.array());
System.out.println("* " + info.trim() +" *");
}
}
iterator.remove();
}else {
// System.out.println("没有可用的通道~");
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
//启动客户端
NIOClient client = new NIOClient();
//启动线程
new Thread(() -> {
while (true) {
client.readMsg();
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}).start();
//发送数据 给服务器
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String s = scanner.nextLine();
client.sendMsg(s);
}
}
}
服务端
public class NIOServer {
/**
* 1、编写服务器端
* 2、服务器启动并监听6667
* 3、服务器接收客户端信息,并实现转发(处理上线和下线)
* 4、编写客户端
*/
private Selector selector;
private ServerSocketChannel serverSocketChannel;
private SocketChannel socketChannel;
private static final int port = 6667;
//构造
public NIOServer(){
//初始化的工作
try {
//得到选择器
selector = Selector.open();
//serverSocketChannel =
serverSocketChannel = serverSocketChannel.open();
//绑定端口
serverSocketChannel.socket().bind(new InetSocketAddress(port));
//设置非阻塞
serverSocketChannel.configureBlocking(false);
//将该serverSocketChannel 注册到selector上
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}catch (IOException e){
e.printStackTrace();
}
}
//监听
public void listen(){
try {
//循环处理
while (true) {
int count = selector.selectNow();
if (count > 0) {
//有事件处理
//遍历得到的selectionKey 集合
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()){
//取出key
SelectionKey key = keyIterator.next();
if (key.isAcceptable()) {
//处理连接
SocketChannel accept = serverSocketChannel.accept();
accept.configureBlocking(false);
//注册
accept.register(selector, SelectionKey.OP_READ);
//给出上线提示
System.out.println("上线 *****"+ accept.getRemoteAddress());
}
if (key.isReadable()) {
//通道发生可读事件了
readData(key);
}
//当前的key删除 防止重复处理
keyIterator.remove();
}
}
}
}catch (IOException e){
e.printStackTrace();
}finally {
}
}
//读取客户端消息
private void readData(SelectionKey key){
//定义一个socketChannel
SocketChannel channel = null;
try {
//得到channel
channel = (SocketChannel) key.channel();
//创建缓冲buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
//得到一个长度
int count = channel.read(buffer);
if (count > 0) {
//把缓冲区转成字符串输出
String msg = new String(buffer.array());
System.out.println("form 客户端 " + msg.trim());
//像其他的客户端转发消息
sendInfoToOtherClients(msg, channel);
}
}catch (Exception e){
try {
System.out.println(channel.getRemoteAddress() + "离线了。。");
//取消注册
key.cancel();
//关闭通道
channel.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
//转发
private void sendInfoToOtherClients(String msg, SocketChannel channel){
System.out.println(" 服务器转发消息中~~");
//遍历 所有注册到selectorChannel 上 socketChannel 排除自己
selector.selectedKeys().forEach(key -> {
//取出通道
SocketChannel targetChannel = (SocketChannel) key.channel();
//排除自己
if (targetChannel instanceof SocketChannel && targetChannel != channel) {
//转发
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
try {
targetChannel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) {
NIOServer nioServer = new NIOServer();
nioServer.listen();
}
}