An echo server example implemented using Java IO, NIO, Netty, respectively

Source: Internet
Author: User

Use Java IO, Java NIO, Netty to implement a simple echoserver (that is, returning the client's input information as is).

Java IO
int port = 9000;  ServerSocket ss = new ServerSocket (port), while (true) {final socket socket = ss.accept (), New Thread (new Runnable () {public  void Run () {while (true) {try {bufferedinputstream in = new Bufferedinputstream (Socket.getinputstream ()); byte[] buf = new Byte[1024];int len = In.read (BUF); Read message from clientstring message = new String (buf, 0, Len); Bufferedoutputstream out = new Bufferedoutputstream (Socket.getoutputstream ()); Out.write (Message.getbytes ()); Echo to Clientout.flush ();} catch (IOException e) {e.printstacktrace ();}}}}). Start ();}

The actual effect is demonstrated with Telnet, as follows:

$ telnet 127.0.0.1 9000Trying 127.0.0.1...Connected to 127.0.0.1.Escape character is ' ^] '. Hihi Hello, hello.

Java IO Disadvantages:

You need to create a thread for each client connection.

Java NIO
Serversocketchannel sschannel = serversocketchannel.open ();int port = 9001; Sschannel.bind (new inetsocketaddress (port)); Selector selector = selector.open (); sschannel.configureblocking (false); SsChannel.register ( selector, selectionkey.op_accept);  //Register Listener connection request while  (True)  {selector.select ();//blocking   Until an event registered by a channel is triggered Set<selectionkey> keys = selector.selectedkeys ();for  ( Selectionkey key : keys)  {if  (key.isacceptable ())  { // Client connection Request serversocketchannel ssc =  (Serversocketchannel)  key.channel (); Socketchannel sc = ssc.accept (); sc.configureblocking (false); Sc.register (selector,  Selectionkey.op_read);  //Register Listener Client Input}if (key.isreadable ()) { //Client input socketchannel sc =  ( Socketchannel)  key.channel (); Bytebuffer buffer = bytebuffer.allocate (1024x768); sc.read (buffer); Buffer.flip (); sc.write (buffer);}} KeYs.clear ();} 

Advantages:

Event drivers can manage multiple connections (channel) through one thread

But be aware that not every scenario is nio better than IO.

Netty
public class nettyechoserver {public class echoserverhandler extends  channelhandleradapter {@Overridepublic  void channelread (channelhandlercontext ctx,  object msg)  { //ehco to clientctx.write (msg); Ctx.flush ();} @Overridepublic  void exceptioncaught (Channelhandlercontext ctx, throwable cause)  {// Close the connection when an exception is  Raised.cause.printStackTrace (); Ctx.close ();}} Private int port;public nettyechoserver (Int port)  {this.port = port;} Public void run ()  throws exception {eventloopgroup bossgroup = new  nioeventloopgroup ();  eventloopgroup workergroup = new nioeventloopgroup (); try  {serverbootstrap b = new serverbootstrap ();  b.group (BossGroup, workerGroup ). Channel (nioserversocketchannel.cl). Childhandler (new channelinitializer<socketchannel> ()  {  @Overridepublic  void  initchannel (Socketchannel ch) Throws exception {ch.pipeline (). AddLast (new  Echoserverhandler ());}). Option (channeloption.so_backlog, 128)  .childoption (channeloption.so_keepalive, true);  //  bind and start to accept incoming connections. Channelfuture f = b.bind (port). Sync (); // wait until the server  socket is closed.// in this example, this does not happen,  but you can do that to gracefully shut down your  Server.f.channel (). Closefuture (). sync ();  finally {workergroup.shutdowngracefully (); bossgroup.shutdowngracefully ();}} Public static void main (String[] args)  throws exception {int port  = 9002;new nettYechoserver (Port). Run ();}} 

The previous example is excerpted from the official documentation.

Advantages:

It seems that you only need to inherit channelhandleradapter and then overwrite the appropriate method.

Reference Documentation:

Http://en.wikipedia.org/wiki/Non-blocking_I/O_ (Java)

Https://today.java.net/pub/a/today/2007/02/13/architecture-of-highly-scalable-nio-server.html

Http://www.javaworld.com/article/2078654/java-se/java-se-five-ways-to-maximize-java-nio-and-nio-2.html

Http://netty.io/wiki/user-guide-for-5.x.html





An echo server example implemented using Java IO, NIO, Netty, respectively

Related Article

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.