Asyncweb Principle Analysis (iii) -- iohandler of Mina

Source: Internet
Author: User

This article analyzes how asyncweb works with the iohandler of Mina.

General Mina server class:

The main class is as follows:

   IoAcceptor acceptor = new NioSocketAcceptor();   acceptor.getFilterChain().addLast("logger", new LoggingFilter());   acceptor.getFilterChain().addLast(     "codec",     new ProtocolCodecFilter(new TextLineCodecFactory(Charset       .forName("UTF-8"))));   acceptor.setHandler(new TimeServerHandler());   acceptor.getSessionConfig().setReadBufferSize(2048);   acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);   acceptor.bind(new InetSocketAddress(8080));

TimeserverhandlerClass:

public class TimeServerHandler extends IoHandlerAdapter {@Overridepublic void exceptionCaught(IoSession session, Throwable cause)    throws Exception {   cause.printStackTrace();}@Overridepublic void messageReceived(IoSession session, Object message)    throws Exception {   String str = message.toString();   System.out.println("Message read:");   System.out.println(str);   Date date = new Date();   session.write(date.toString());   System.out.println("Message written...");   session.close();}@Overridepublic void sessionIdle(IoSession session, IdleStatus status)    throws Exception {   System.out.println("IDLE " + session.getIdleCount(status));}}

General process: Initialize niosocketacceptor -- Add filter -- set Handler -- set session attribute -- BIND. After startupTimeserverhandlerSlaveIohandleradapterThe Inheritance Method in it to process data.

Methods In asyncweb:

MinatransportStart () in the class ()

package org.apache.asyncweb.server.transport.minapublic void start() throws TransportException {ioHandler = new DefaultHttpIoHandler();ioHandler.setContainer( container );acceptor = new NioSocketAcceptor(ioThreads);eventExecutor = new OrderedThreadPoolExecutor(this.eventThreads);boolean success = false;try {DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();chain.addFirst("threadPool", new ExecutorFilter(eventExecutor));acceptor.setReuseAddress(true);acceptor.getSessionConfig().setReuseAddress(true);chain.addLast("mdc", new MdcInjectionFilter());if (isLoggingTraffic) {LOG.debug("Configuring traffic logging filter");LoggingFilter filter = new LoggingFilter();filter.setSessionClosedLogLevel(logLevel);filter.setExceptionCaughtLogLevel(logLevel);filter.setMessageReceivedLogLevel(logLevel);filter.setMessageSentLogLevel(logLevel);filter.setSessionClosedLogLevel(logLevel);filter.setSessionCreatedLogLevel(logLevel);filter.setSessionIdleLogLevel(logLevel);filter.setSessionOpenedLogLevel(logLevel);acceptor.getFilterChain().addLast("logging", filter);}// TODO make this configurable instead of hardcoding like thisacceptor.setBacklog(100);acceptor.setHandler(ioHandler);if (address != null) {acceptor.bind(new InetSocketAddress(address, port));} else {acceptor.bind(new InetSocketAddress(port));}success = true;LOG.debug("NIO HTTP Transport bound on port " + port);} catch (IOException e) {throw new TransportException("NIOTransport Failed to bind to port "+ port, e);} finally {if (!success) {acceptor.dispose();acceptor = null;}}}

Package Org. apache. asyncweb. server. transport. mina; public class defaulthttpiohandler extends implements httpiohandler {/** the default idle time in seconds-5 minutes */public static final int default_idle_time = 300; Public defaulthttpiohandler () {super (New Factory (); // constructor of the parent class. The parameter must implement the singlesessioniohandlerfactory interface} // implements setcontainer () public in httpiohandler. Servicecontainer getcontainer () {return (factory) getfactory ()). getcontainer ();} public void setcontainer (servicecontainer container) {(factory) getfactory ()). setcontainer (container);} public void setreadidle (INT idletime) {(factory) getfactory ()). setreadidle (idletime);} // generate the singlesessioniohandler factory method, while singlesessioniohandler is used to process specific sessions. Private Static class factory implements singlesessioniohandlerfactory {private servicecontainer container; private int readidletime = default_idle_time; Public servicecontainer getcontainer () {return container;} public void setcontainer (servicecontainer container) {This. container = container;} public void setreadidle (INT idletime) {This. readidletime = idletime;} // implement the gethandler method of singlesessioniohandlerfactory, public singlesessioniohandler gethandler (iosession session) {singlehttpsessioniohandler handler = new singlehttpsessioniohandler (container, session); handler. setreadidletime (readidletime); Return handler ;}}}

Class diagram:



Summary:PassDefaulthttpiohandlerFinally, the implementation class singlehttpsessioniohandler of iohandler is generated,

It contains three ingested objects.Servicecontainer,Iosession,Readidletime.

Data is processed through the filter responsibility chain.

Because you must first parse HTTP and jump to the correctHttpservice.

Coming soon:Asyncweb Principle Analysis (iv) -- HTTP Parsing

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.