Mina use of the UDP chapter

Source: Internet
Author: User
Tags bind socket

What is Mina.

Mina is a Java non-blocking communication mode framework (http://hi.baidu.com/yhzhw2121/blog/item/61506c420efb7a189313c619.html here is a detailed description of the difference between non-blocking and blocking communication), developed by the Apache organization. At present, this kind of open source framework has a lot of advantages and disadvantages of the reason why I chose Mina because he came from the hands of Apache.

This article mainly describes the Mina version of 2.0M6 can be http://mina.apache.org/index.html here to download the latest version of Mina.

On the internet about Mina little information, UDP way less, the following is a few days I learn a brief summary of the demo will continue to improve, I hope to provide some help to beginners, but also hope that the hero to guide, first thanked •

The program is mainly divided into server side and Clinet end

Server is implemented by Mina, clinet driven by Java common UDP link (Mina can also implement clinet side)

Server end is divided into two parts, part of the listener side, and the other part of the processing end (Mina used in the other jar package has Slf4j-jdk,slf4j-api)

Listener-Side code:

public class Memorymonitortest {

Private static final long serialversionuid = 1L;

public static final int PORT = 8080;

Public Memorymonitortest () throws IOException {

Niodatagramacceptor acceptor = new Niodatagramacceptor ();//Create a UDP receiver
Acceptor.sethandler (New Yourhandler ());//Set handler for receiver

Executor ThreadPool = Executors.newfixedthreadpool (1500);//Build thread pool
Acceptor.getfilterchain (). AddLast ("Exector", New Executorfilter (ThreadPool));
Acceptor.getfilterchain (). AddLast ("Logger", New Loggingfilter ());

Datagramsessionconfig dcfg = Acceptor.getsessionconfig ();//Establish a connection configuration file
Dcfg.setreadbuffersize (4096);//Set receive maximum bytes default 2048
Dcfg.setreceivebuffersize (1024);//Set the size of the input buffer
Dcfg.setsendbuffersize (1024);//Setting the output buffer size
Dcfg.setreuseaddress (TRUE);//Set the port for each non-master listener connection to be reused

Acceptor.bind (New Inetsocketaddress (port));//Bind Port
}


public static void Main (string[] args) throws IOException {
New Memorymonitortest ();
}

After the server establishes the connection, the server side--"filter--" handler

Processing-Side code:

public class Yourhandler extends Iohandleradapter {

Messagesent is the event that the server fires after it responds to clinet success

@Override
public void Messagesent (iosession session, Object message) throws Exception {
if (message instanceof Iobuffer) {
Iobuffer buffer = (iobuffer) message;
byte[] bb = Buffer.array ();
for (int i = 0; i < bb.length; i++) {
System.out.print ((char) bb[i]);
}
}
}

Throwing an exception-triggered event

@Override
public void Exceptioncaught (iosession session, Throwable Cause)
Throws Exception {
Cause.printstacktrace ();
Session.close (TRUE);
}

Server received an event triggered by a UDP request

@Override
public void Messagereceived (iosession session, Object message)
Throws Exception {
System.out.println ("messagereceived");
if (message instanceof Iobuffer) {
Iobuffer buffer = (iobuffer) message;
byte[] bb = Buffer.array ();
for (int i=0;i<bb.length;i++) {
System.out.print ((char) bb[i]);
//            }
Iobuffer buffer1 = Iobuffer.wrap ("one". GetBytes ());//return information to the clinet end
Session.write (Buffer1);

Declare here that the message must be of type Iobuffer
}

}

Connection Shutdown Event triggered

@Override
public void Sessionclosed (Iosession session) throws Exception {
System.out.println ("Session closed ...");
}

Establish connection-triggered events

@Override
public void Sessioncreated (Iosession session) throws Exception {
System.out.println ("Session created ...");
SocketAddress remoteaddress = session.getremoteaddress ();
System.out.println (remoteaddress);

}

Session Idle

@Override
public void Sessionidle (iosession session, Idlestatus status)
Throws Exception {
SYSTEM.OUT.PRINTLN ("Session idle ...");
}

Open connection-triggered event, which differs from sessioncreated in that one connection address (a) the first time the server establishes a session the default time-out is 1 minutes, If the timeout is not reached at this time, the connection address (a) is sessionopened when the request is sent to the server again (a) when the request is sent to the server for the first time, or when the connection times out, both sessioncreated and Sessionopene are triggered when the request is sent to the server D two events)

@Override
public void sessionopened (Iosession session) throws Exception {
System.out.println ("Session opened ...");
SocketAddress remoteaddress = session.getremoteaddress ();
System.out.println (remoteaddress);
}

Client-side code: Client-side code does not explain

public void Send (String host, int port) {

try {
InetAddress ia = inetaddress.getbyname (host);
Datagramsocket socket = new Datagramsocket (9999);
Socket.connect (IA, port);
byte[] buffer = new byte[1024];

Buffer = ("22")
. GetBytes ();
Datagrampacket DP = new Datagrampacket (buffer, buffer.length);
System.out.println (Dp.getlength ());
Datagrampacket DP1 = new Datagrampacket (new byte[22312], 22312);
Socket.send (DP);
Socket.receive (DP1);
byte[] bb = Dp1.getdata ();
for (int i = 0; i < dp1.getlength (); i++) {
System.out.print ((char) bb[i]);
}
} catch (Exception e) {
E.printstacktrace ();
}
}

Note: UDP is a no-connection protocol, so Clinet sends a request to the server to be immediately disconnected, the server side of the session must be set to a time-out system default is one minute, if you need to keep the connection can let the client set the heartbeat (Clinet heartbeat time <=server End Session Timeout time)

Reference:
http://blog.csdn.net/junhuo/archive/2008/10/20/3106260.aspx http://amozon.javaeye.com/blog/ 326169 
http://mina.apache.org/udp-tutorial.html 
http://topic.csdn.net/u/20080910/12/ 9538228d-0b18-40f3-96b8-c2221ac9f9cc.html
and the practice and Mina source code in the Mina package.

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.