TCP persistent connection and short connection instance based on Apache Mina

Source: Internet
Author: User
Tags socket error
1. Preface

Apache Mina is an excellent project organized by Apache. Mina is the abbreviation of multipurpose infrastructure for networkapplications. It is a network application framework that helps users easily develop high-performance and high-reliability network applications. This article describes how to use Apache mina2.0 to implement TCP persistent connections and short connection applications.

2. system introduction 2.1 System Framework

The entire system consists of two server programs and two client programs. TCP persistent connection and short connection communication are implemented respectively.

The system business logic is to establish a persistent connection between a client and the server, and establish a short connection between a client and the server. Data is sent from the short connection client to the persistent connection client through the server, and the response data is received from the persistent connection client. Disconnect after receiving the response data.

The system architecture diagram is as follows:

2.2 handling process

The system process is as follows:

1) Start the server program and listen to ports 8001 and 8002.

2) The persistent Connection Client establishes a connection to port 8002 of the server, and the server saves the connection object to the shared memory. Because the persistent connection mode is used, the connection object is unique.

3) The short Connection Client establishes a connection to the server port 8001. Create a connection object after the connection is established.

4) send data after the client connection is successful. After receiving the data, the server obtains the persistent connection object from the shared memory, which is used to send data to the persistent connection client. Set the short connection object as the property value of the long connection object before sending.

5) The persistent Connection Client returns response data after receiving the data. The server obtains the short connection object from the properties of the persistent connection object, and sends the response data to the short Connection Client.

6) The short connection client closes the connection after receiving the response data.

3. The server program 3.1 connects to the server for a long time

Service Startup

Public classMinalongconnserver {

Private Static final int Port= 8002;

Public voidStart ()ThrowsIoexception {

Ioacceptor acceptor =NewNiosocketacceptor ();

 

Acceptor. getfilterchain (). addlast ("logger ",NewLoggingfilter ());

Acceptor. getfilterchain (). addlast ("codec ",NewProtocolcodecfilter (NewTextlinecodecfactory (charset.Forname("UTF-8 "))));

 

Acceptor. sethandler (NewMinalongconnserverhandler ());

Acceptor. getsessionconfig (). setreadbuffersize (2048 );

Acceptor. BIND (NewInetsocketaddress (Port));

System.Out. Println ("listeningon port" +Port);

}

}

Message Processing

Public classMinalongconnserverhandlerExtendsIohandleradapter {

Private FinalLogger logger = (logger) loggerfactory.Getlogger(Getclass ());

 

@ Override

Public voidSessionopened (iosession session ){

Inetsocketaddress remoteaddress = (inetsocketaddress) Session. getremoteaddress ();

String clientip = remoteaddress. getaddress (). gethostaddress ();

Logger.info ("longconnect server opened session ID =" + String.Valueof(Session. GETID ()));

Logger.info ("receive connection from client:" + clientip + .");

Initialization init = initialization.Getinstance();

Hashmap <string, iosession> clientmap = init. getclientmap ();

Clientmap. Put (clientip, session );

}

 

@ Override

Public voidMessagereceived (iosession session, object message ){

Logger.info ("messagereceived in the long connect server ..");

String expression = message. tostring ();

Logger.info ("message is:" + expression );

Iosession resume connsession = (iosession) Session. getattribute ("Reset connsession ");

Logger.info ("Connect connect Server session ID =" + String.Valueof(Required connsession. GETID ()));

Define connsession. Write (expression );

}

 

@ Override

Public voidSessionidle (iosession session, idlestatus status ){

Logger.info ("disconnectingthe idle .");

// Disconnect an idle Client

Session. Close (True);

}

 

@ Override

Public voidExceptioncaught (iosession session, throwable cause ){

// Close the connection onexceptional situation

Logger. Warn (cause. getmessage (), cause );

Session. Close (True);

}

}

3.2 Short connection Server

Service Startup

Public classMinashortconnserver {

Private Static final int Port= 8001;

Public voidStart ()ThrowsIoexception {

Ioacceptor acceptor =NewNiosocketacceptor ();

 

Acceptor. getfilterchain (). addlast ("logger ",NewLoggingfilter ());

Acceptor. getfilterchain (). addlast ("codec ",NewProtocolcodecfilter (NewTextlinecodecfactory (charset.Forname("UTF-8 "))));

 

Acceptor. sethandler (NewMinashortconnserverhandler ());

Acceptor. getsessionconfig (). setreadbuffersize (2048 );

Acceptor. getsessionconfig (). setidletime (idlestatus.Both_idle, 3 );

Acceptor. BIND (NewInetsocketaddress (Port));

System.Out. Println ("listeningon port" +Port);

}

}

Message Processing

Public classMinashortconnserverhandler
Extends
Iohandleradapter {

Private FinalLogger logger = (logger) loggerfactory.Getlogger(Getclass ());

 

@ Override

Public voidSessionopened (iosession session ){

Inetsocketaddress remoteaddress = (inetsocketaddress) Session. getremoteaddress ();

Logger.info (remoteaddress. getaddress (). gethostaddress ());

Logger.info (string.Valueof(Session. GETID ()));

}

 

@ Override

Public voidMessagereceived (iosession session, object message ){

Logger.info ("messagereceived in the short connect server ...");

String expression = message. tostring ();

Initialization init = initialization.Getinstance();

Hashmap <string, iosession> clientmap = init. getclientmap ();

If(Clientmap =Null| Clientmap. Size () = 0 ){

Session. Write ("error ");

}Else{

Iosession longconnsession =Null;

Iterator <string> iterator = clientmap. keyset (). iterator ();

String key = "";

While(Iterator. hasnext ()){

Key = iterator. Next ();

Longconnsession = clientmap. Get (key );

}

Logger.info ("Connect connect Server session ID:" + String.Valueof(Session. GETID ()));

Logger.info ("longconnect Server session ID:" + String.Valueof(Longconnsession. GETID ()));

Longconnsession. setattribute ("Reset connsession", session );

Longconnsession. Write (expression );

}

}

 

@ Override

Public voidSessionidle (iosession session, idlestatus status ){

Logger.info ("disconnectingthe idle .");

// Disconnect an idle Client

Session. Close (True);

}

 

@ Override

Public voidExceptioncaught (iosession session, throwable cause ){

// Close the connection onexceptional situation

Logger. Warn (cause. getmessage (), cause );

Session. Close (True);

}

}

 

4. Client Program 4.1 persistent connection to the client

Use java.net. socket to establish a connection to the server. After the socket is established, the connection is maintained. After receiving the data packet from the server, the original text is directly returned.

Public classTcpkeepaliveclient {

PrivateString IP;

Private intPort;

Private StaticSocketSocket=
Null
;

Private Static int Timeout= 50*1000;

 

PublicTcpkeepaliveclient (string IP,
Int
Port ){

This. IP = IP;

This. Port = port;

}

 

Public voidReceiveandsend ()ThrowsIoexception {

Inputstream input =Null;

Outputstream output =Null;

 

Try{

If(Socket=Null|Socket. Isclosed () |!Socket. Isconnected ()){

Socket=NewSocket ();

Inetsocketaddress ADDR =NewInetsocketaddress (IP, Port );

Socket. Connect (ADDR,Timeout);

Socket. Setsotimeout (Timeout);

System.Out. Println ("tcpkeepaliveclientnew ");

}

 

Input =Socket. Getinputstream ();

Output =Socket. Getoutputstream ();

 

// Read body

Byte[] Receivebytes ={}; // array of received packets

While(True){

If(Input. Available ()> 0 ){

Receivebytes =New byte[Input. Available ()];

Input. Read (receivebytes );

 

// Send

System.Out. Println ("tcpkeepaliveclientsend Date:" +NewString (receivebytes ));

Output. Write (receivebytes, 0, receivebytes. Length );

Output. Flush ();

}

}

 

}Catch(Exception e ){

E. printstacktrace ();

System.Out. Println ("tcpclientnew socket error ");

}

}

 

Public static voidMain (string [] ARGs)
Throws
Exception {

Tcpkeepaliveclient client =NewTcpkeepaliveclient ("127.0.0.1", 8002 );

Client. receiveandsend ();

}

 

}

4.2 short Connection Client

Service Startup

Public classMinashortclient {

Private Static final int Port= 8001;

 

Public static voidMain (string [] ARGs)
Throws
Ioexception, interruptedexception {

Ioconnector conne=NewNiosocketconnector ();

Connector. getsessionconfig (). setreadbuffersize (2048 );

 

Connector. getfilterchain (). addlast ("logger ",NewLoggingfilter ());

Connector. getfilterchain (). addlast ("codec ",NewProtocolcodecfilter (NewTextlinecodecfactory (charset.Forname("UTF-8 "))));

 

Connector. sethandler (NewMinashortclienthandler ());

For(IntI = 1; I <= 10; I ++ ){

Connectfuture future = connector. Connect (NewInetsocketaddress ("127.0.0.1 ",Port));

Future. awaituninterruptibly ();

Iosession session = Future. getsession ();

Session. Write (I );

Session. getclosefuture (). awaituninterruptibly ();

 

System.Out. Println ("result =" + session. getattribute ("result "));

}

Connector. Dispose ();

 

}

}

Message Processing

Public classMinashortclienthandlerExtendsIohandleradapter {

Private FinalLogger logger = (logger) loggerfactory.Getlogger(Getclass ());

 

PublicMinashortclienthandler (){

}

 

@ Override

Public voidSessionopened (iosession session ){

}

 

@ Override

Public voidMessagereceived (iosession session, object message ){

Logger.info ("messagereceived in the client ..");

Logger.info ("message is:" + message. tostring ());

Session. setattribute ("result", message. tostring ());

Session. Close (True);

}

 

@ Override

Public voidExceptioncaught (iosession session, throwable cause ){

Session. Close (True);

}

}

5. Summary

Through the example in this article, Apache Mina can implement TCP persistent connections and short connections on the server. The client only implements the short connection mode, and the long connection mode can also be implemented (the traditional Java Socket mode is used in this article ). There may be a better way to transmit connection objects between two servers through shared memory.

 

Engineering: http://download.csdn.net/detail/peterwanghao/5306972

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.