Server
PackageCom.server;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.ServerSocketChannel;ImportJava.nio.channels.SocketChannel; Public classServer { Public Static voidMain (string[] args)throwsException {//new TCP service sideServersocketchannel Serversocketchannel =Serversocketchannel.open (); //Binding TCP PortsServersocketchannel.socket (). Bind (NewInetsocketaddress (9999)); //configured as "non-blocking"Serversocketchannel.configureblocking (false); while(true) { //allow TCP links to be receivedSocketchannel Socketchannel =serversocketchannel.accept (); //When there is a TCP connection, the fetch is not empty if(Socketchannel! =NULL) { //writing English Data "life is not a step, fighting is endless"String NewData = System.currenttimemillis () + ": Cease to struggle and your cease to live."; //Open CacheBytebuffer buf = bytebuffer.allocate (1024); //Reset , ready to write data to the cachebuf.clear (); //actually writing data to the cacheBuf.put (Newdata.getbytes ()); //preparing to read data from the cacheBuf.flip (); //If you read the data with the remaining while(Buf.hasremaining ()) {//actually reads the data from the cache and writes it to the channelSocketchannel.write (BUF); } } } }}
Client
Packagecom.client;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SocketChannel; Public classClient { Public Static voidMain (string[] args)throwsException {//new TCP service sideSocketchannel Socketchannel =Socketchannel.open (); //link to local 8888 portSocketchannel.connect (NewInetsocketaddress ("localhost", 8888)); //Open CacheBytebuffer buf = bytebuffer.allocate (1024); //Reset , ready to write data to the cachebuf.clear (); //actually reads data from the channel to the cache intBytesread =Socketchannel.read (BUF); //preparing to read data from the cacheBuf.flip (); //If you read the data with the remaining while(Buf.hasremaining ()) {//Take one byte byteB = (byte) (Buf.get ()); //turn into a characterSystem.out.print ((Char) b); } //Close ChannelSocketchannel.close (); }}
Java NIO Primer "original"