Mina client and server-side code authoring __java

Source: Internet
Author: User
Tags sessions throwable log4j

1. Client
1.1 Writing Clients

Package com.boonya.protocol;  
Import java.net.InetSocketAddress;  
Import Java.nio.charset.Charset;  
Import Org.apache.log4j.Logger;  
Import Org.apache.mina.core.future.ConnectFuture;  
Import Org.apache.mina.core.service.IoConnector;  
Import org.apache.mina.core.session.IoSession;  
Import Org.apache.mina.filter.codec.ProtocolCodecFilter;  
Import Org.apache.mina.filter.codec.textline.LineDelimiter;  
Import Org.apache.mina.filter.codec.textline.TextLineCodecFactory;  
Import Org.apache.mina.transport.socket.nio.NioSocketConnector;  
  
Import Com.boonya.protocol.handler.request.ClientMessageHandler;  
  
    public class MyClient {private static Logger Logger = Logger.getlogger (Myclient.class);  
  
    private static String HOST = "127.0.0.1";  
  
    private static int PORT = 8900; public static void Main (string[] args) {//Create a client client that is not set up ioconnector connector = new Niosocketconne  
        ctor (); Set the link timeout time Connector.setconnecttimEoutmillis (30000); Add Filter Connector.getfilterchain (). AddLast (//Add message Filter "codec",//Mina self-band TEXTLINECODEC filter based on text line break codec see \ r \ n Think a complete message ends the new Protocolcodecfilter (new Textlinecodecfactory Chars ET. forname ("UTF-8"), LineDelimiter.WINDOWS.getValue (), Linedelimiter.  
        Windows.getvalue ()));  
        Add business Logic Processor Class Connector.sethandler (new Clientmessagehandler ());  
        Iosession session = NULL;  
            try {connectfuture future = Connector.connect (new inetsocketaddress (HOST, PORT); Future.awaituninterruptibly ();  
            Wait for connection creation Complete session = Future.getsession ();  
        Session.write ("Mina");  
        catch (Exception e) {logger.info ("Client link exception ...");  
        } session.getclosefuture (). awaituninterruptibly ();  
     Logger.info ("Mina to be closed");   Connector.dispose ();
 }  
  
}


1.2 Client-side logical processing

Package com.boonya.protocol.handler.request;  
Import Org.apache.log4j.Logger;  
Import Org.apache.mina.core.service.IoHandlerAdapter;  
Import org.apache.mina.core.session.IoSession;  
  
public class Clientmessagehandler extends Iohandleradapter {  
  
    private static Logger Logger = Logger.getlogger ( Clientmessagehandler.class);  
  
    public void messagereceived (iosession sessions, Object message)  
            throws Exception {  
        String msg = message.tostring ( );  
        Logger.info ("The information received by the client is:" + msg);  
    }  
  
    @Override public  
    void Exceptioncaught (iosession session, Throwable Cause)  
            throws Exception {  
        Logger.info ("The client has an exception ..." + cause);  
    }  
  


2. Service-side
2.1 Writing Service side

Package com.boonya.protocol;  
Import java.net.InetSocketAddress;  
Import Java.nio.charset.Charset;  
Import Org.apache.log4j.Logger;  
Import Org.apache.mina.core.service.IoAcceptor;  
Import Org.apache.mina.core.session.IdleStatus;  
Import Org.apache.mina.filter.codec.ProtocolCodecFilter;  
Import Org.apache.mina.filter.codec.textline.LineDelimiter;  
Import Org.apache.mina.filter.codec.textline.TextLineCodecFactory;  
Import Org.apache.mina.filter.logging.LoggingFilter;  
Import Org.apache.mina.transport.socket.nio.NioSocketAcceptor;  
  
Import Com.boonya.protocol.handler.response.ServerMessageHandler;  
  
    public class Myserver {private static Logger Logger = Logger.getlogger (Myserver.class);  
  
    private static int PORT = 8900;  
        public static void Main (string[] args) {//Create a socket ioacceptor acceptor = null on a non-blocking server side;  
            try {acceptor = new niosocketacceptor (); Set Log Filter ACCEPTOR.GEtfilterchain (). AddLast ("Logger", New Loggingfilter ()); Acceptor.getfilterchain (). AddLast (//Add message Filter "codec",//Mina self-coded T with Text line feed  
                            EXTLINECODEC filter see \ r \ n Think a complete message ends the new Protocolcodecfilter (New Textlinecodecfactory (Charset  
                            . forname ("UTF-8"), LineDelimiter.WINDOWS.getValue (),  
            LineDelimiter.WINDOWS.getValue ()));  
            Sets the size of the buffer to read Data Acceptor.getsessionconfig (). Setreadbuffersize (2048);  
            No operation in read Channel 10s into idle state acceptor.getsessionconfig (). Setidletime (Idlestatus.both_idle, 10);  
            Binding Logic Processor Acceptor.sethandler (new Servermessagehandler ());  
            Binding Port Acceptor.bind (new Inetsocketaddress (port)); Logger.info ("Server started successfully.")  
  
        The port number is: "+ port";  catch (Exception e) {e.printstacktrace ();
        }  
    }
 



2.2 service-side business processing

Package com.boonya.protocol.handler.response;  
Import Java.util.Date;  
Import Org.apache.log4j.Logger;  
Import Org.apache.mina.core.service.IoHandlerAdapter;  
Import Org.apache.mina.core.session.IdleStatus;  
  
Import org.apache.mina.core.session.IoSession; public class Servermessagehandler extends Iohandleradapter {public static Logger Logger = Logger.getlogger (Serve  
  
    Rmessagehandler.class);  
    public void Sessioncreated (Iosession session) throws Exception {logger.info ("server-side creates connection with client");  
    The public void sessionopened (Iosession session) throws Exception {Logger.info ("The server is open with the client connection ...");  
        public void messagereceived (iosession sessions, Java.lang.Object message) throws Exception {  
        String msg = message.tostring ();  
        Logger.info ("The data received by the server is:" + msg);  
        if ("Bye". Equals (msg)) {//server fracture condition Session.close (true);  
        Date date = new Date (); Session.Write (date); public void Messagesent (iosession sessions, Object message) throws Exception {Logger.info ("The service side sent a message successfully.  
  
    ..");  
    } public void Sessionidle (iosession session, Idlestatus status) throws Java.lang.Exception {logger.  
    Info ("The server goes into idle State ..."); public void Exceptioncaught (iosession session, Throwable cause) throws Exception {Logg  
    Er.info ("service-side Send exception ..." +cause);  
    public void Sessionclosed (Iosession session) throws Exception {Logger.info ("close connection ..."); }  
  
}

 

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.