Apache Mina Getting Started (iii)--Client synchronous communication

Source: Internet
Author: User
Tags crc32 getmessage socket

After two previous articles,
Apache Mina Primer (i)-basics
Apache Mina Getting Started (ii.)--Asynchronous communication mechanism
We have a basic understanding of Mina: Mina is an asynchronous communication framework, and for server-side development, long-connected, asynchronous communication uses Mina very convenient. But there are also requirements that may require the use of a short connection, i.e. each connection requires the following four steps: Connect-send-receive-disconnect.
Mina clients that use short connections no longer need the Iohandler messagereceived method to process business data, but instead transform them into short connections that accept messages for business data processing. How to do it. We only need to set Mina's Usereadoperation property to True.
Service-side code is not subject to change. See Apache Mina Getting Started (ii.)--Asynchronous communication mechanism this article is available.

Synchronizing client code

/** * Mina Client Synchronous Communication * Principle: Mina asynchronous communication is to establish an effective long connection, client communication in a long connection, * for Mina client synchronization operation, the long connection transformation is a short connection, that is, each operation of the client needs to establish a connection, send messages, receive messages, disconnect * @author Liuc * @date 2017-12-20 * */public class Clienttest {public static void main (string[] args) throws MinaC Onnecttimeoutexception, Minareadtimeoutexception {//Connection object Niosocketconnector Connector = new Niosocketconn
        Ector ();
        Set the connection timeout time Connector.setconnecttimeoutmillis (30000L); Add Filter Connector.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New COM.ONION.MINA.CLI Ent.
        Bytearraycodecfactory ()));
        Socketsessionconfig cfg = Connector.getsessionconfig ();
        The Mina client that implements the synchronization must have the Usereadoperation property set to True Cfg.setusereadoperation (true);

        Iosession session = NULL; 
        Connector.setdefaultremoteaddress (New Inetsocketaddress ("127.0.0.1", 8888));//Set Default Access address//Join a re-connect mechanism, re-connect 5 times, throw an exception if not re-connected
           for (int num = 0;num < 5; num++) {try {     Connectfuture future = Connector.connect (); Future.awaituninterruptibly (); Wait for the connection to be created successfully session = Future.getsession ();
                            Gets the session if (session.isconnected ()) {System.out.println ("Connection service side" + "127.0.0.1" + ":" + 8888 + "[into
                                    "+", Time: "+ new SimpleDateFormat (" Yyyy-mm-dd HH:mm:ss ")
                    . Format (New Date ()));
                Break
                                }} catch (Runtimeioexception e) {System.out.println ("Connection service side"
                                + "127.0.0.1" + ":" + 8888 + "Failed" + ", Time:" + new Simpledat Eformat ("yyyy-mm-dD HH:mm:ss "). Format (new Date ()) +", connecting the socket service exception
                , please check the socket port, IP is correct, MSG service is started, exception content: "+ e.getmessage ());
                    try {thread.sleep (1000);//After connection failure, reconnect interval 5s} catch (Interruptedexception E1) {
                E1.printstacktrace ();
            } throw new Minaconnecttimeoutexception ("Connection socket service exception, please check socket port, IP is correct, MSG service is started");
                            }} if (!session.isconnected ()) {System.out.println ("Connection service side"
                            + "127.0.0.1" + ":" + 8888 
                                    + "Failed" + ", Time:" + new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss") . Format (New Date ()) + ", connecting the socket service exception, check the socket port, IP is correct, MWhether the SG service is started, ");
        Read timeout throw new minaconnecttimeoutexception ("Connection socket service exception, please check socket port, IP is correct, MSG service is started");
            }//The connection is now implemented, followed by send-receive-disconnect try {basemessageforserver message = new Basemessageforserver ();
            String content = "Hello world!";
            CRC32 CRC = New CRC32 ();
            try {crc.update (content.getbytes ("GBK"));
            } catch (Unsupportedencodingexception e) {e.printstacktrace ();
            } message.setfuncid (5);
            Message.setpacketidcode (10000);
            Message.setcontent (content);
            Message.setcheckcode (Crc.getvalue ());
            Message.setlength (Content.getbytes (). length);
            Send Session.write (message). awaituninterruptibly ();
        Doread (session);
            } finally {//disconnects session.close (true);
            Session.getservice (). Dispose ();
  Connector.dispose ();      }} public static void Doread (Iosession session) throws Minareadtimeoutexception {//Receive Re
        Adfuture readfuture = Session.read (); if (readfuture.awaituninterruptibly (10000, timeunit.seconds)) {//SYSTEM.OUT.PRINTLN ("Client receives message
            : "+ message);

            Object obj = Readfuture.getmessage ();
                if (obj instanceof basemessageforclient) {basemessageforclient client = (basemessageforclient) obj;
                SYSTEM.OUT.PRINTLN ("Client received message:" + client.tostring ());
                    if (client.getfuncid () = = 4) {//Received heartbeat packet System.out.println ("Received heartbeat Packet");
                Session.write ("1111"); }}} else {//Read timeout throw new minareadtimeoutexception ("read data timeout from socket, please check MSG service
        The service side is normal "); }
    }



}

The

can be tested using this client. Code Source download Address: http://download.csdn.net/download/u012151597/10166224

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.