Demo demo of UDP bidirectional communication based on NETTY4 in service end

Source: Internet
Author: User
Tags documentation getmessage
Objective

The prevalence of NIO frameworks makes it possible to develop large concurrent and high-performance Internet services. The most popular of these is Mina and Netty, and Mina's current major version is MINA2, and Netty's main version is Netty3 and Netty4 (Netty5 has been canceled: see this article).

This article will demonstrate a complete example of two-way communication based on the Netty4 UDP server and a standard UDP client (Java implementation). In fact, Netty4 's UDP example is very hard to find (forgive me for being stupid, looking for the whole network also has no valuable code, there is also Netty3, and Netty3 and Netty4 style is not a little bit, the reference meaning is not small), the official code demo only a simple example of UDP broadcast, Not enough to demonstrate Netty4 best practices for UDP communications.

"Highlights of this article"

Netty4 's UDP example is too hard to find:
Netty4 full bi-directional UDP communication examples are difficult to find (not official), this article is to use code to demonstrate this;
In this case, there is no 3rd party dependency for client UDP implementations:
In the case of Mina or Netty, clients are also using Mina or Netty client lib, and this article will use standard UDP code directly (easy Cross-platform implementation, such as iOS platform), not dependent on the 3rd party package;
Complete executable source code, easy to learn:
Full demo source code, suitable for beginners to run directly, easy to learn and research.

"Digression"

The community is often debating whether to use Mina or netty, such as these articles: "Open source NIO framework gossip-whether it is Mina first or Netty first", "about why Choose Netty" 11 Questions and Answers, " Choose Netty or Mina: Deep Research and contrast (i), haha it is really difficult to choose. However, the personal point of view is that the familiar with which it, there is nothing to tangle, will be two and more than the essence of the difference, are also from the same author's hand.
Write a demo of what.

Back to the end, this article to demonstrate the demo contains two parts, the Java UDP client and the Netty4 UDP server, the client will every 3 seconds to send a message to the server, and the server immediately after receiving the message to reply to a message to the client.

In other words, both the server and the client have to implement the sending and receiving of messages, which realizes two-way communication. If the heart, a little change, it is easy to implement a simple chat program. The following section gives the real implementation code.
Netty4 service-Side preparation work

"1" First step: Download Netty4

Netty4 's official website is: http://netty.io/, directly under the latest Netty 4.1 bar, the following figure:

Introduction to NIO Framework (i): Server-side based on Netty4 UDP two-way communication demo demo _qq20160615-0.png

"2" Step two: Find Netty4 's core library files

Directly with this all in one jar bag bar, anyway used in the service side, 2M size of things do not matter, convenient management, see the following figure:

Introduction to NIO Framework (i): Server-side based on Netty4 UDP two-way communication demo demo _qq20160615-1.png

"3" Third step: to build a Java project ready to open the

I personally used to use eclipse, you use NetBeans or Intelij also no problem, the specific establishment of the process is not proficient in the garment itself Baidu Bar, the only attention is to the Netty4 Lib package reference in the line, I see the following figure:

"Service-side Code"

"1" service-side main class Echoserver.java:
public class Echoserver
{
public static void Main (string[] args) throws Interruptedexception
{
Bootstrap B = new Bootstrap ();
Eventloopgroup Group = new Nioeventloopgroup ();
B.group (Group)
. Channel (Niodatagramchannel.class)
. Handler (new Echoseverhandler ());

Server-side listening on port 9999
B.bind (9999). sync (). Channel (). Closefuture (). await ();
}
}

As shown in the preceding code: I have to say, Netty4 's UDP server code is really simple to implement, a Bootstrap, a eventloopgroup, plus a simplechannelinboundhandler, It's easy to get Netty4 (and, exactly, Netty4 is encapsulated on Java NIO, but the end API is really friendly to developers).

Spit a slot: said Netty4 's code compared to Mina, the style is really very different, although there is a deep stream, but after Netty3, Netty4 evolution, the difference between the two (at least the code looks like) is very obvious. In addition, B.bind (9999). sync (). Channel (). Closefuture (). await () This large series of sequential method calls, it looks very strange, accidentally adjusted incorrectly, the server will not explode.

"2" service End handler class Echoseverhandler:
public class Echoseverhandler extends simplechannelinboundhandler<datagrampacket>
{
@Override
protected void channelRead0 (Channelhandlercontext ctx, Datagrampacket packet)
Throws Exception
{
Read the Received data
Bytebuf buf = (bytebuf) packet.copy (). Content ();
byte[] req = new byte[buf.readablebytes ()];
Buf.readbytes (req);
String BODY = new String (req, charsetutil.utf_8);
System.out.println ("note" >>>>>> receive data from the client: "+body);"

Reply to a message to the client
Ctx.writeandflush (New Datagrampacket (
Unpooled.copiedbuffer ("Hello, I'm a server, my timestamp is" +system.currenttimemillis ()
, Charsetutil.utf_8)
, Packet.sender ()). sync ();
}
}

As shown above, this handler looks like a similar implementation of Mina, much simpler.

"Client Code"

To make the client code look more concise, I extracted the socket management code into the Localudpsocketprovider class and extracted the UDP data listening and receiving The Localudpdatareciever class (actually the two classes with the same name are simplified from MOBILEIMSDK engineering OH).

"1" Client main class Echoclient.java:
public class Echoclient
{
public static void Main (string[] args) throws Exception
{
Initialize the socket for local UDP
Localudpsocketprovider.getinstance (). Initsocket ();
Start local UDP listening (for receiving data)
Localudpdatareciever.getinstance (). startup ();

Loop sending data to the server
while (true)
{
The data to send
String toserver = "Hi, I am the client, my timestamp" +system.currenttimemillis ();
byte[] Soserverbytes = toserver.getbytes ("UTF-8");

Start sending
Boolean OK = Udputils.send (soserverbytes, soserverbytes.length);
if (OK)
LOG.D ("Echoclient", "the information sent to the service side has been delivered.");
Else
LOG.E ("Echoclient", "the information sent to the service side has not been successfully issued ...) ");

3,000 seconds into the next cycle.
Thread.Sleep (3000);
}
}
}

Supplemental Note: The client code does not use any dependencies, the pure Java UDP Code implementation (if is the Andriod platform, the code also almost does not have to change to be able to use), the partial code modifies from the open source instant communication frame MOBILEIMSDK (removes many to be guaranteed the robustness code, now looks is much simpler, Easy for beginners to learn).

"2" Socket operation class Localudpsocketprovider.java:
public class Localudpsocketprovider
{
private static final String TAG = LocalUDPSocketProvider.class.getSimpleName ();
private static Localudpsocketprovider instance = NULL;
Private Datagramsocket localudpsocket = null;

public static Localudpsocketprovider getinstance ()
{
if (instance = null)
Instance = new Localudpsocketprovider ();
return instance;
}

public void Initsocket ()
{
Try
{
UDP Local Listening port (if 0 will be indicated by system allocation, otherwise use specified port)
This.localudpsocket = new Datagramsocket (configentity.localudpport);
When you call connect, Datagrampacket does not need to design the IP and port of the target host each time you send
* Note: The Connect method must be called before the Datagramsocket.receive () method,
* Otherwise, the entire send data will be incorrectly blocked. This may be the official API bug, or it may be a tune
* This should be the case with the specification, but no official explanation is found
This.localUDPSocket.connect (
Inetaddress.getbyname (Configentity.serverip), configentity.serverudpport);
This.localUDPSocket.setReuseAddress (TRUE);
LOG.D (TAG, "New Datagramsocket () completed successfully.");
}
catch (Exception e)
{
LOG.W (TAG, "Localudpsocket created an error, because:" + e.getmessage (), E);
}
}

Public Datagramsocket Getlocaludpsocket ()
{
return this.localudpsocket;
}
}

"3" Data receive class Localudpdatareciever.java:
public class Localudpdatareciever
{
private static final String TAG = LocalUDPDataReciever.class.getSimpleName ();
private static Localudpdatareciever instance = NULL;
Private thread thread = NULL;

public static Localudpdatareciever getinstance ()
{
if (instance = null)
Instance = new Localudpdatareciever ();
return instance;
}

public void Startup ()
{
This.thread = new Thread (new Runnable ()
{
public void Run ()
{
Try
{
LOG.D (Localudpdatareciever.tag, "Local UDP port listening, port =" + Configentity.localudpport + "...");

Start listening
LocalUDPDataReciever.this.udpListeningImpl ();
}
catch (Exception eee)
{
LOG.W (Localudpdatareciever.tag, "Local UDP monitor stopped (socket is closed?)," + eee.getmessage (), EEE);
}
}
});
This.thread.start ();
}

private void Udplisteningimpl () throws Exception
{
while (true)
{
byte[] data = new byte[1024];
Packets that receive datagrams
Datagrampacket packet = new Datagrampacket (data, data.length);

Datagramsocket localudpsocket = Localudpsocketprovider.getinstance (). Getlocaludpsocket ();
if ((Localudpsocket = null) | | (localudpsocket.isclosed ()))
Continue

Block until data is received
Localudpsocket.receive (packet);

Parsing the data sent from the service side.
String pfromserver = new String (Packet.getdata (), 0, Packet.getlength (), "UTF-8");
LOG.W (Localudpdatareciever.tag, "note" >>>>>> received the message from the service side: "+pfromserver);
}
}
}

"Run Effect"

Client Run Results:
Introduction to NIO Framework (i): Server-side based on Netty4 UDP two-way communication demo demo _qq20160615-3.png

Server-side Run results:
Introduction to NIO Framework (i): Server-side based on Netty4 UDP two-way communication demo demo _qq20160615-4.png

"Supplementary Notes"

The client code is nothing special, it is standard Java UDP code, it looks different from other examples because I have refined it, there is no essential difference. The same code changes can also be used very well on the Android side. In fact, the client code above is extracted from the Java side of the open source MOBILEIMSDK, and you can also look at its Android, server, and iOS terminals, simplifying what you can use for your own purposes.

"More Learning Resources"

[1] The source of Mina and Netty online learning and Consulting:
mina-2.x address is: http://docs.52im.net/extend/docs/src/mina2/
mina-1.x address is: http://docs.52im.net/extend/docs/src/mina1/
netty-4.x address is: http://docs.52im.net/extend/docs/src/netty4/
netty-3.x address is: http://docs.52im.net/extend/docs/src/netty3/

[2] Mina and Netty API documentation online:
mina-2.x API Documentation (online edition): http://docs.52im.net/extend/docs/api/mina2/
mina-1.x API Documentation (online edition): http://docs.52im.net/extend/docs/api/mina1/
netty-4.x API Documentation (online edition): http://docs.52im.net/extend/docs/api/netty4/
netty-3.x API Documentation (online edition): http://docs.52im.net/extend/docs/api/netty3/

[3] More information on the programming of NIO:
Please enter the essence record: http://www.52im.net/forum.php?mod=collection&action=view&ctid=9

[4] information about IM chat applications, message push technology:
Please enter the essence record: Http://www.52im.net/forum.php?mod=collection&op=all

[5] Technical exchange and learning:
Direct access to the Instant Messaging developer community to discuss and learn about network programming, IM chat applications, and the development of message push applications.

"Complete source project Download"

For complete Eclipse Source Engineering please contact the author or go to the link http://www.52im.net/thread-367-1-1.html to download it yourself.

(This article is published synchronously in: http://www.52im.net/thread-367-1-1.html)

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.