java编写的客户端与服务器,会把客户端上线和下线,来自客户端的消息转发给其它客户端,服务器上也可以显示
服务器
public class NioServer {
private static Map<String,SocketChannel>clientMap=new HashMap();
//消息量不大,连接比较多
public static void main (String[] args) throws Exception{
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);//配置为非阻塞
ServerSocket serverSocket=serverSocketChannel.socket();
serverSocket.bind(new InetSocketAddress(8899));
Selector selector=Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true){
try{
selector.select();
Set<SelectionKey> selectionKeySet=selector.selectedKeys();
selectionKeySet.forEach(selectionKey->{
try{
final SocketChannel client;
if (selectionKey.isAcceptable()){
ServerSocketChannel server =(ServerSocketChannel)selectionKey.channel();
client=server.accept();
client.configureBlocking(false);
client.register(selector,SelectionKey.OP_READ);
String key ="["+ UUID.randomUUID().toString()+"]";
clientMap.put(key,client);
}else if (selectionKey.isReadable()){
client=(SocketChannel)selectionKey.channel();
ByteBuffer readBuffer=ByteBuffer.allocate(1024);
int count =client.read(readBuffer);
if (count>0){
readBuffer.flip();
Charset charset=Charset.forName("utf-8");
String recievedMessage=String.valueOf(charset.decode(readBuffer).array());
System.out.println(client+": "+recievedMessage);
String senderKey=null;
for (Map.Entry<String,SocketChannel>entry: clientMap.entrySet()){
if(client==entry.getValue()){
senderKey=entry.getKey();
break;
}
}
for (Map.Entry<String,SocketChannel>entry: clientMap.entrySet()){
SocketChannel value =entry.getValue();
ByteBuffer writeBuffer=ByteBuffer.allocate(1024);
writeBuffer.put((senderKey+": "+recievedMessage).getBytes());
writeBuffer.flip();
value.write(writeBuffer);
}
}
}
}catch (Exception ex){
ex.printStackTrace();
}
});
selectionKeySet.clear();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
}
Client
public class NioClient {
public static void main(String[] args) throws Exception {
try {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
Selector selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_CONNECT);//
socketChannel.connect(new InetSocketAddress("127.0.0.1", 8899));
while (true) {
selector.select();
Set<SelectionKey> keySet = selector.selectedKeys();
for (SelectionKey selectionKey : keySet) {
if (selectionKey.isConnectable()) {
SocketChannel client = (SocketChannel) selectionKey.channel();
if (client.isConnectionPending()) {
client.finishConnect();
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
writeBuffer.put((LocalDateTime.now() + "连接成功").getBytes());
writeBuffer.flip();
client.write(writeBuffer);
ExecutorService executorService = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
executorService.submit(() -> {
while (true) {
try {
writeBuffer.clear();
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(input);
String sendMessage = br.readLine();
writeBuffer.put(sendMessage.getBytes());
writeBuffer.flip();
client.write(writeBuffer);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
client.register(selector, SelectionKey.OP_READ);//注册读取
} else if (selectionKey.isReadable()) {
SocketChannel client = (SocketChannel) selectionKey.channel();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int count = client.read(readBuffer);
if (count > 0) {
String recieveMessage = new String(readBuffer.array(), 0, count);
System.out.println(recieveMessage);
}
}
}
keySet.clear();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}