Interaction between the java nio SocketChannel server and multiple clients (chat function)

Source: Internet
Author: User

Server: Java code: import java. io. IOException; import java.net. inetSocketAddress; import java.net. serverSocket; import java.net. socket; import java. nio. byteBuffer; import java. nio. channels. selectionKey; import java. nio. channels. selector; import java. nio. channels. serverSocketChannel; import java. nio. channels. socketChannel; import java. nio. charset. charset; import java. util. hashMap; import java. util. map; Import java. util. set; public class NIOSServer {private int port = 8888; // decodes buffer private Charset cs = Charset. forName ("gbk");/* accept data buffer */private static ByteBuffer sBuffer = ByteBuffer. allocate (1024);/* send data buffer */private static ByteBuffer rBuffer = ByteBuffer. allocate (1024);/* ing client channel */private Map <String, SocketChannel> clientsMap = new HashMap <String, SocketChannel> (); private static Se Lector selector; public NIOSServer (int port) {this. port = port; try {init ();} catch (Exception e) {e. printStackTrace () ;}} private void init () throws IOException {/** start the server end, configure to be non-blocking, bind the port, and register the accept event * ACCEPT event: this event is triggered when the server receives a Client Connection Request */ServerSocketChannel serverSocketChannel = ServerSocketChannel. open (); serverSocketChannel. configureBlocking (false); ServerSocket serverSocket = serverSocketChannel. s Ocket (); serverSocket. bind (new InetSocketAddress (port); selector = Selector. open (); serverSocketChannel. register (selector, SelectionKey. OP_ACCEPT); System. out. println ("server start on port:" + port);}/*** server round robin listener, the select method is blocked until related events occur or times out */private void listen () {while (true) {try {selector. select (); // The returned value is the number of events triggered this time. Set <SelectionKey> selectionKeys = selector. selectedKeys (); for (SelectionKey ke Y: selectionKeys) {handle (key);} selectionKeys. clear (); // clear the processed event} catch (Exception e) {e. printStackTrace (); break ;}}/ *** process different events */private void handle (SelectionKey selectionKey) throws IOException {ServerSocketChannel server = null; SocketChannel client = null; string effecetext = null; int count = 0; if (selectionKey. isAcceptable () {/** client request connection event * serversocket establishes a socket connection for the client T register the READ event and listen to the client input * READ event: this event is triggered when the client sends data and has been correctly READ by the control thread of the server */server = (ServerSocketChannel) selectionKey. channel (); client = server. accept (); client. configureBlocking (false); client. register (selector, SelectionKey. OP_READ);} else if (selectionKey. isReadable () {/** READ event. After receiving the data sent by the client, register the listening client */client = (SocketChannel) selectionKey. channel (); rBuffer. clear (); count = client. read (rBuffer ); If (count> 0) {rBuffer. flip (); paietext = String. valueOf (cs. decode (rBuffer ). array (); System. out. println (client. toString () + ":" + receiveText); dispatch (client, receiveText); client = (SocketChannel) selectionKey. channel (); client. register (selector, SelectionKey. OP_READ) ;}}}/*** push current client information to other clients */private void dispatch (SocketChannel client, String info) throws IOException {Socket s = clien T. socket (); String name = "[" + s. getInetAddress (). toString (). substring (1) + ":" + Integer. toHexString (client. hashCode () + "]"; if (! ClientsMap. isEmpty () {for (Map. Entry <String, SocketChannel> entry: clientsMap. entrySet () {SocketChannel temp = entry. getValue (); if (! Client. equals (temp) {sBuffer. clear (); sBuffer. put (name + ":" + info ). getBytes (); sBuffer. flip (); // output to the temp channel. write (sBuffer) ;}} clientsMap. put (name, client);} public static void main (String [] args) throws IOException {NIOSServer server = new NIOSServer (7777); server. listen () ;}} client, which can run and start multiple clients: Java code: import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; I Mport 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. date; import java. util. set; public class NIOClient {/* send data buffer */private static ByteBuffer sBuffer = ByteBuffer. allocate (1024);/* accept data buffer */private static ByteBuffer rBuffer = ByteBuffer. allocate (1024);/* Service Device address */private InetSocketAddress SERVER; private static Selector selector; private static SocketChannel client; private static String receiveText; private static String sendText; private static int count = 0; public NIOClient (int port) {SERVER = new InetSocketAddress ("localhost", port); init ();} public void init () {try {/** the client initiates a connection request to the server */SocketChannel socketChannel = SocketChannel. open (); s OcketChannel. configureBlocking (false); selector = Selector. open (); socketChannel. register (selector, SelectionKey. OP_CONNECT); socketChannel. connect (SERVER);/** polling listener client registration event occurrence */while (true) {selector. select (); Set <SelectionKey> keySet = selector. selectedKeys (); for (final SelectionKey key: keySet) {handle (key) ;}; keySet. clear () ;}} catch (Exception e) {e. printStackTrace () ;}} public stati C void main (String [] args) throws IOException {NIOClient client = new NIOClient (7777);} private void handle (SelectionKey selectionKey) throws IOException {if (selectionKey. isConnectable () {/** connection establishment event, successfully connected to the server */client = (SocketChannel) selectionKey. channel (); if (client. isConnectionPending () {client. finishConnect (); System. out. println ("connect success! "); SBuffer. clear (); sBuffer. put (new Date (). toLocaleString () +" connected! "). GetBytes (); sBuffer. flip (); client. write (sBuffer); // send the message to the server/* Original article from webmaster * the startup thread keeps listening to the client input. If you are confident that the input will be sent to the server * because the input stream is blocked, so a separate Thread listens */new Thread () {@ Override public void run () {while (true) {try {sBuffer. clear (); InputStreamReader input = new InputStreamReader (System. in); BufferedReader br = new BufferedReader (input); sendText = br. readLine ();/** WRITE events not registered, because most of the time the channel can WRITE */sBuffer. put (sendText. getBytes (); sBuffer. flip (); client. write (sBuffer);} catch (IOException e) {e. printStackTrace (); break ;}}};}. start ();} // register the read event client. register (selector, SelectionKey. OP_READ);} else if (selectionKey. isReadable () {/** read event trigger * contains information sent from the server side. After reading the information and outputting it to the screen, continue to register the read event * Listen to the server sending information */client = (SocketChannel) selectionKey. channel (); rBuffer. clear (); count = client. read (rBuffer); if (count> 0) {paietext = new String (rBuffer. array (), 0, count); System. out. println (receiveText); client = (SocketChannel) selectionKey. channel (); client. register (selector, SelectionKey. OP_READ );}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.