首先是服务端代码
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 (IOException e){ e.printStackTrace(); } } //监听 public void listen(){ try { while(true){ int count = selector.select(2000); if (count>0){ //修相关的事件处理 Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while(iterator.hasNext()){ SelectionKey key = iterator.next(); if(key.isAcceptable()){ SocketChannel socketChannel = listenChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(selector,SelectionKey.OP_READ); System.out.println(socketChannel.getRemoteAddress()+"上线了"); } if(key.isReadable()){//通道发生read事件,通道可读状态 readData(key); } iterator.remove(); } }else { continue; // System.out.println("服务器等待中"); } } }catch (Exception e){ e.printStackTrace(); }finally { } } //读取客户端消息 private void readData(SelectionKey selectionKey){ //定义一个 SocketChannel socketChannel = null; try { socketChannel = (SocketChannel)selectionKey.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int count = socketChannel.read(buffer); if(count>0){ //把缓冲区的数据转会字符串 String msg = new String(buffer.array()); System.out.println("from client"+msg.trim()); //向其他客户端转发消息 sendInfo(msg,socketChannel); } }catch (IOException e){ try { System.out.println(socketChannel.getRemoteAddress()+"离线了"); selectionKey.cancel(); socketChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } } } //转发消息给其他客户 private void sendInfo(String msg,SocketChannel self) throws IOException { System.out.println("服务器转发消息"); //遍历所有注册到selector的SocketChannel for(SelectionKey key : selector.keys()){ Channel tagetChannel = key.channel(); if(tagetChannel instanceof SocketChannel && tagetChannel!=self){ SocketChannel dest =(SocketChannel)tagetChannel; ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); dest.write(buffer); } } } public static void main(String[] args) throws IOException { GroupChatServer groupChatServer = new GroupChatServer(); groupChatServer.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() throws IOException { 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..."); } public void sendInfo(String info){ info = username +":"+info; try{ socketChannel.write(ByteBuffer.wrap(info.trim().getBytes(StandardCharsets.UTF_8))); }catch (IOException e){ e.printStackTrace(); } } public void readInfo(){ try{ int select = selector.select(2000); if(select>0){ Iterator<SelectionKey> iterator = selector.selectedKeys().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()); System.out.println(msg.trim()); }else { continue; } iterator.remove(); } } }catch (IOException e){ e.printStackTrace(); } } public static void main(String[] args) throws IOException { GroupChatClient chatClient = new GroupChatClient(); new Thread(){ public void run(){ while(true){ chatClient.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(); chatClient.sendInfo(s); } } }