服务端
package com.huwc.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ChatServer {
private Selector selector ;
private ServerSocketChannel serverChannel ;
private static final int PORT = 6666 ;
private Map<SocketChannel, String> usernameMap = new HashMap<>();
public ChatServer() {
try {
selector = Selector.open();
serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false) ;
serverChannel.bind(new InetSocketAddress(PORT));
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
listen();
return;
} catch (IOException e) {
e.printStackTrace();
}
}
public void listen() {
while (true){
int count = 0;
try {
count = selector.select();
} catch (IOException e) {
e.printStackTrace();
}
if(count > 0){
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while(iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
if(selectionKey.isAcceptable()){
try {
SocketChannel socketChannel = serverChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
System.out.println(socketChannel.getRemoteAddress() + " 上线了");
} catch (IOException e) {
e.printStackTrace();
}
}
if(selectionKey.isReadable()){
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
try {
ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
buffer.clear();
int readCount = socketChannel.read(buffer);
buffer.flip();
if(readCount > 0){
String message = new String(buffer.array(), 0, buffer.limit());
if(message.startsWith("name:")){
String username = message.replaceAll("name:","");
usernameMap.put(socketChannel, username);
transferMessage(socketChannel.getRemoteAddress()+" 改名为:" + username, socketChannel);
}else {
//转发给所有的客户端
transferMessage(message, socketChannel);
}
}
} catch (IOException e) {
try {
System.out.println(socketChannel.getRemoteAddress().toString().substring(1) + " 下线了");
selectionKey.cancel();
socketChannel.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
iterator.remove();
}
}else {
}
}
}
private void transferMessage(String message, SocketChannel selfChannel) throws IOException {
Set<SelectionKey> keys = selector.keys();
for (SelectionKey key : keys) {
Channel channel = key.channel();
if(channel instanceof SocketChannel && channel != selfChannel){
String username = usernameMap.get(selfChannel);
if(null == username || username.equals("")){
username = ((SocketChannel) channel).getRemoteAddress().toString().substring(1);
}
String msg = username + " 说: " + message ;
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
try {
((SocketChannel) channel).write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws IOException {
ChatServer server = new ChatServer();
server.listen();
}
}
客户端
package com.huwc.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 ChatClient {
private final String HOST = "127.0.0.1" ;
private final int PORT = 6666 ;
private Selector selector ;
private SocketChannel socketChannel ;
private String username ;
public ChatClient() {
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 (IOException e) {
e.printStackTrace();
}
}
public void sendInfo(String info){
try {
socketChannel.write(ByteBuffer.wrap(info.getBytes()));
}catch (IOException e){
}
}
public void readInfo(){
try {
int count = selector.select();
if(count > 0){
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while(iterator.hasNext()){
SelectionKey key = iterator.next();
if(key.isReadable()){
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
String msg = new String(buffer.array(), 0, buffer.limit());
System.out.println(msg.trim());
}
iterator.remove();
}
}else {
}
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
ChatClient client = new ChatClient();
//启动一个线程,进行数据的读取
Thread thread = new Thread(){
@Override
public void run() {
while (true){
client.readInfo();
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
//发送数据
Scanner scanner = new Scanner(System.in) ;
while (scanner.hasNextLine()){
String msg = scanner.nextLine();
client.sendInfo(msg);
}
}
}
测试截图