1. server
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; import java.util.Set; public class GroupChatServer { private Selector selector; private ServerSocketChannel listenChannel; private static final int PORT = 8888; // constructor public GroupChatServer () { the try { selector = Selector.open(); listenChannel = ServerSocketChannel.open (); // bind port listenChannel.socket () the bind (. new new the InetSocketAddress (PORT)); // set nonblocking mode listenChannel.configureBlocking ( to false ); // the listenChannel registered Selector listenChannel. register (selector, SelectionKey.OP_ACCEPT); } catch (Exception e) { e.printStackTrace (); } } /** * Monitor * / Public void the listen () { the try { the while ( to true ) { // SELECT (2000) blocked only two seconds // int COUNT = the selector.select (2000); // SELECT () method blocks int COUNT = Selector. SELECT (); IF (COUNT> 0 ) { // iterate to get all SelectionKey set the Iterator <SelectionKey> keysIterator = selector.selectedKeys () Iterator ();. the while (keysIterator.hasNext ()) { //Each processing SelectionKey the SelectionKey SelectionKey = keysIterator.next (); // monitored connection event IF (selectionKey.isAcceptable ()) { SocketChannel socketChannel = listenChannel.accept(); socketChannel.configureBlocking(false); //注册 socketChannel.register(selector, SelectionKey.OP_READ); // 提示上线 System.out.println(socketChannel.getRemoteAddress() + "上线"); } // channel-readable event IF (selectionKey.isReadable ()) { // TODO processing the read readMessage (selectionKey); } // delete key, to prevent duplication process keysIterator.remove (); } } The else { // System.out.println ( "Waiting ...."); } } } catch (Exception e) { e.printStackTrace (); } } /** * Read the client message * * @param key */ public void readMessage(SelectionKey key) { SocketChannel socketChannel = null; try { socketChannel = (SocketChannel) key.channel(); ByteBuffer the ByteBuffer = ByteBuffer.allocate (1024 ); int read = socketChannel.read (ByteBuffer); // do the processing according to the read value, if the read> 0 described really read the data IF (read> 0 ) { String message = new String(byteBuffer.array()); System.out.println ( "Form1 Client:" + Message); // TODO forward messages to other client sendInfoToOtherClient (message, socketChannel); } } catch (IOException e) { try { System.out.println (socketChannel.getRemoteAddress () + "off the ..." ); // cancel the registration after offline key.cancel (); // close the Channel socketChannel.close (); } catch (IOException e1) { e1.printStackTrace (); } } } /** * Forward messages to other clients * * @Param the Message forwarding messages * @param self : 排除的channel */ public void sendInfoToOtherClient(String message, SocketChannel self) throws IOException { System.out.println ( "server forwards the message ..." ); // loop through all registered to socketChannel on the selector, and rule out the Set <SelectionKey> Keys = Selector.keys (); for (SelectionKey Key: Keys) { // taken by the corresponding key of the SocketChannel Channel targetChannel = key.channel (); // rule out IF (targetChannel the instanceof the SocketChannel targetChannel = &&! Self) { Target the SocketChannel = (the SocketChannel) targetChannel; // the message stored in the buffer the ByteBuffer buffer = ByteBuffer.wrap (message.getBytes ()); // the data in the write channel buffer target.write (buffer); } } } public static void main (String [] args) { // create the object GroupChatServer ChatServer = new new GroupChatServer (); chatServer.listen(); } }
2. Client
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 GroupChatClient { // 服务器ip private final String HOST = "127.0.0.1"; // 服务器端口 private final int PORT = 8888; private Selector selector; private SocketChannel socketChannel; private String username; public GroupChatClient() { 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 + " ok!"); } catch (Exception e) { e.printStackTrace (); } } /** * Send a message to the server * * @Param info message content * / public void sendInfo (String info) { info = username + "说:" + info; try { socketChannel.write(ByteBuffer.wrap(info.getBytes())); } catch (IOException e) { e.printStackTrace (); } } /** * Reads the message from the server */ public void readInfo() { try { int readChannels = selector.select(2000); if (readChannels > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> keyInterator = keys.iterator(); while (keyInterator.hasNext()) { SelectionKey the SelectionKey = keyInterator.next (); IF (selectionKey.isReadable ()) { // get the read associated channel the SocketChannel SocketChannel = (the SocketChannel) selectionKey.channel (); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); socketChannel.read(byteBuffer); // data buffer is transferred into a string String messge = new new String (byteBuffer.array ()); System.out.println( messge.trim()); } // delete the current SelectionKey keyInterator.remove (); } } The else { // System.out.println ( ".... channel not available") } } catch (IOException e) { e.printStackTrace (); } } public static void main (String [] args) { // Start the client GroupChatClient ChatClient = new new GroupChatClient (); // start over from the server transmits read data thread every 2 seconds a new new the Thread () { @Override public void run() { while (true) { chatClient.readInfo(); try { Thread.currentThread().sleep(2000); } catch (InterruptedException e) { e.printStackTrace (); } } } }.start(); // send data to the server Scanner Scanner = new new Scanner (the System.in); the while (Scanner.hasNext ()) { String info = scanner.next(); chatClient.sendInfo(info); } } }