Recently looking at the Netty framework, incidentally wrote the NIO Socketchannel server and client
Server.java
Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.ServerSocketChannel;ImportJava.nio.channels.SocketChannel;/*** Created by Guanxianseng on 2017/8/18.*/ Public classServer {Private Static voidReadmessage ()throwsIOException {serversocketchannel server=Serversocketchannel.open (); Server.socket (). Bind (NewInetsocketaddress (8888)); while(true) {Socketchannel client=server.accept (); Bytebuffer Buffer= Bytebuffer.allocate (1024); Client.read (buffer); System.out.println ("Server Received msg =" +NewString (Buffer.array ())); SendMessage (client); } } Private Static voidSendMessage (Socketchannel client)throwsIOException {bytebuffer buffer= Bytebuffer.allocate (1024); String msg= "Server time =" +System.currenttimemillis (); Buffer.put (Msg.getbytes ()); Buffer.flip (); Client.write (buffer); } Public Static voidMain (string[] args)throwsIOException {readmessage (); }}
Client.java
Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SocketChannel;/*** Created by Guanxianseng on 2017/8/18.*/ Public classClient {Private StaticSocketchannel client =NULL; Static { Try{init (); } Catch(IOException e) {e.printstacktrace (); } } Private Static voidInit ()throwsIOException {Client=Socketchannel.open (); Client.connect (NewInetsocketaddress ("127.0.0.1", 8888)); } Private Static voidSendMessage (String message)throwsIOException {bytebuffer buffer= Bytebuffer.allocate (1024); Buffer.put (Message.getbytes ()); Buffer.flip (); while(Buffer.hasremaining ()) {client.write (buffer); }//client.close (); } Private Static voidReadmessage () {Thread reader=NewThread (NewRunnable () {@Override Public voidrun () {Bytebuffer buffer= Bytebuffer.allocate (1024); Try{client.read (buffer);//Buffer.flip ();System.out.println (NewString (Buffer.array ())); } Catch(IOException e) {e.printstacktrace (); } } }); Reader.start (); } Public Static voidMain (string[] args)throwsIOException {sendMessage ("Hello NiO"); Readmessage (); }}
The whole routine is the same as the socket and ServerSocket routines, which is blocked form. NiO can be set to non-blocking, which needs to be used in conjunction with selector. This is not the same as the socket, ServerSocket.
Niosocket Server Client