"Write a common server program in Java" 02 Listener

Source: Internet
Author: User

In a server program, the listener acts like a company's foreground, so that the listener spends as little time on each new connection as possible to ensure the fastest response.

Back to the programming itself:

1. The listener is best run by a separate thread

2. After the listener has received a new connection, the method of processing the connection needs to return as soon as possible

In the Java Push Framework, two types of listeners are defined: acceptor and monitoracceptor, because they need to listen to both the normal client and the server monitoring service clients.

Since the logic of the listening section is the same, the abstract class listener is first defined to implement the function of the monitor, and the part that handles the socket is defined as an abstract method.

// abstract method for handling sockets protected Abstract Boolean handleacceptedsocket (            pushclientsocket clientsocket);

The implementation of the monitoring function is relatively simple, or the three steps: Create,bind,accept.

    Private Booleandolistening (inetsocketaddress serveraddr) {BooleanRET =false; intSocketbuffersize =Getserverimpl (). Getserveroptions (). Getsocketbuffersize (); intSocketType =Getserverimpl (). Getserveroptions (). Getsockettype (); Try {            //CreateServerSocket =Socketfactory.getdefault (). Createserversocket (SocketType, socketbuffersize); //BindServersocket.bind (SERVERADDR); Debug.debug ("Start to listen" + serveraddr.gethostname () + ":" +Serveraddr.getport ()); //Acceptdoaccept (); RET=true; } Catch(IOException e) {e.printstacktrace (); if(ServerSocket! =NULL) {serversocket.close (); ServerSocket=NULL; }        }                returnret; }

Consider that there are several different sockets in Java: Synchronous blocking sockets, synchronous non-blocking sockets, and JDK7 newly added asynchronous sockets, which are not convenient for switching between different types of sockets if you use the socket class directly from Java. So I've customized the Pushserversocket and pushclientsocket two new interfaces:

// for a server socket, only the required bind and accept are defined , // and a close that does not throw an exception.  Publicinterface  pushserversocket {    publicvoidthrows  IOException;      Public throws IOException;      Public void close ();}
//the client socket interface is defined in C + + style, because the original code is written in C + +,This definition makes it easy to translate the original C + + code Public InterfacePushclientsocket { PublicString GetIP ();  Public intGetport (); //The direct use of selector here is actually problematic, destined to use only NiO's way//changes will be considered later     PublicSelectionkey Registerselector (Selector Selector,intOps, Object attachment)throwsIOException;  Public intSendbyte[] Buffer,intOffsetintSizethrowsIOException;  Public intRecvbyte[] Buffer,intOffsetintSizethrowsIOException;  Public BooleanIsOpen ();  Public Booleanisconnected ();  Public voidclose ();}

The corresponding NIO version of the implementation is Pushserversocketimpl and Pushclientsocketimpl, code implementation is relatively simple, here is not posted out.

Go back to listener and see doaccept:

    Private voiddoaccept () {//Start a new threadAcceptorthread =NewThread (NewRunnable () { Public voidrun () { while(blnrunning) {Try{pushclientsocket Clientsocket=serversocket.accept (); Debug.debug ("New Client from" +Clientsocket.getip ()); //Start Servicing the Client connection                        if(!Handleacceptedsocket (Clientsocket))                        {Clientsocket.close (); }                    } Catch(IOException e) {e.printstacktrace (); return;                }                }            }                    }); //Start the threadAcceptorthread.start (); }

Here the server socket's accept method implementation is blocked, so that you can avoid polling continuously, so when you implement accept with NIO can not call configureblocking set to non-blocking mode.

The Close method of invoking the server socket directly when the listener is stopped, the Accept method throws an exception to jump out of the loop and ends the listener thread's run.

Do not forget to end the listener by using the thread's Join method to wait for the thread to end.

     Public voidstoplistening () {blnrunning=false; //Close Server Socket        if(ServerSocket! =NULL) {serversocket.close (); ServerSocket=NULL; }                //Wait the thread to terminate        if(Acceptorthread! =NULL) {            Try{acceptorthread.join (); } Catch(interruptedexception e) {//e.printstacktrace ();} acceptorthread=NULL; }    }

Acceptor implementation is relatively complex, need to record access information, do some checking, and then hand over to clientfactory processing:

    protected BooleanHandleacceptedsocket (Pushclientsocket clientsocket) {//Record LogClientfactory Clientfactoryimpl =serverimpl.getclientfactory (); Serverstats Stats=serverimpl.getserverstats (); Serveroptions Options=serverimpl.getserveroptions (); Stats.addtocumul (ServerStats.Measures.VisitorsSYNs,1); //Check whether the maximum number of allowed accesses is reached        if(Clientfactoryimpl.getclientcount () >=options.getmaxconnections ()) {Debug.debug ("Reach maximum clients allowed, deny it"); return false; }        //Check if IP is allowed        if(!clientfactoryimpl.isaddressallowed (Clientsocket.getip ())) {Debug.debug ("IP refused:" +Clientsocket.getip ()); return false; }        //working with sockets        returnclientfactoryimpl.createphysicalconnection (Clientsocket,false, listeneroptions); }

Monitoracceptor implementation is relatively simple, directly to the clientfactory processing can be.

    protected Boolean Handleacceptedsocket (Pushclientsocket clientsocket) {        return  Serverimpl.getclientfactory (). Createphysicalconnection (                true, listeneroptions);    }

The article about Clientfactory's handling logic is detailed in the following articles.

It is easy to implement a listener function, so there are not many things to say.

"Write a common server program in Java" 02 Listener

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.