Network I/O model--04 non-blocking mode (unblock the Accept (), read () method) on the basis of adding multithreading technology

Source: Internet
Author: User
Tags getmessage stringbuffer


Because the application level does not use multithreading, this causes the application to handle the socket socket one-by-one. This socket socket does not finish processing, you can not handle the next socket socket. The problem can be improved by making the processing of socket sockets at the application level not affect each other.

Service-side code

 PackageTestblocksocket;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket;Importjava.net.SocketTimeoutException;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;//by joining the thread concept, the Socket Server can be used at the application level//handle multiple socket sockets simultaneously in a non-blocking manner Public classSocketserver4alltimeoutandmultithread {Private Final StaticLogger Logger = Loggerfactory.getlogger (socketserver4alltimeoutandmultithread.class); Private StaticObject xwait =NewObject ();  Public Static voidMain (string[] args)throwsException {serversocket serversocket=NewServerSocket (8888); Serversocket.setsotimeout (100); Try {             while(true) {Socket Socket=NULL; Try{Socket=serversocket.accept (); } Catch(Sockettimeoutexception el) {// ===================                    //execute here, stating that this accept () method does not receive any TCP connection to the main thread here can do something, recorded as x//==================                    synchronized(socketserver4alltimeoutandmultithread.xwait) {Logger.info ("No TCP connection received this time, wait 10 milliseconds, simulate the processing time of event X"); SocketServer4AllTimeoutAndMultiThread.xWait.wait (10); }                    Continue; }                //The business process can be handed over to a thread (where the thread pool can be used)//Note that the thread creation process is resource-intensive and time-consuming//It 's not going to change. The Accept () method receives the Socket connection only one at aSocketserverthreadwithtimeout Socketserverthread =Newsocketserverthreadwithtimeout (socket); NewThread (Socketserverthread). Start (); }        } Catch(Exception e) {logger.error (E.getmessage (), E); } finally {            if(ServerSocket! =NULL) {serversocket.close (); }        }    }}//of course, after receiving the client Socket, the business process can be handed over to a thread to doclassSocketserverthreadwithtimeoutImplementsRunnable {Private Final StaticLogger Logger = Loggerfactory.getlogger (socketserverthreadwithtimeout.class); Privatesocket socket;  Publicsocketserverthreadwithtimeout (socket socket) { This. Socket =socket; } @Override Public voidrun () {InputStream InputStream=NULL; OutputStream OutputStream=NULL; Try{InputStream=Socket.getinputstream (); OutputStream=Socket.getoutputstream (); Integer Sourceport=Socket.getport (); intMaxLen = 2048; byte[] Contextbytes =New byte[MaxLen]; intReallen; StringBuffer message=NewStringBuffer (); //below we collect information             This. Socket.setsotimeout (10); Bioread: while(true) {                Try {                     while((Reallen = Inputstream.read (contextbytes, 0, maxlen))! =-1) {message.append (NewString (contextbytes, 0, Reallen)); //We also assume that the "over" keyword is read to indicate that the business content transfer is complete                        if(Message.indexof ("over")! =-1) {                             BreakBioread; }                    }                } Catch(sockettimeoutexception E2) {// =================                    //execute here, stating that this read () method does not receive any data stream main thread here again can do something, remember as Y// =================Logger.info ("This time the mission data message is not received, wait 10 ~ cover seconds, simulate the processing time of event Y"); Continue; }            }            //Print information belowLong threadId =Thread.CurrentThread (). GetId (); SocketServerThreadWithTimeOut.LOGGER.info ("Server (thread:" + ThreadId + ") received a message from the port:" + Sourceport + ":" +message); //start sending information belowOutputstream.write ("Postback Response message:". GetBytes ()); //closing in and out objectsInputstream.close ();        Outputstream.close (); } Catch(Exception e) {logger.error (E.getmessage (), E); }    }}


With the introduction of multithreading, the throughput of I/O has been improved (not significantly) because the Accepto method is still in the process of "synchronizing".

Network I/O model--04 non-blocking mode (unblock the Accept (), read () method) on the basis of adding multithreading technology

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.