Netty 3.9.2 UDP server and client DEMO, netty3.9.2

Source: Internet
Author: User

Netty 3.9.2 UDP server and client DEMO, netty3.9.2

Description: implemented based on the netty 3.9.2 udp protocol (If your version is 4. X or 5.X, please refer to other methods); the logic structure of the program is that the client sends A string of data to the server, and the server returns the string "A" to the client ". During Game Development, udp packet loss needs to be processed. You can use the return value of the server to perform related processing to determine whether to resend the packet.

Article structure:

I. Server Side

1. UDPServer

2. UdpChannelPipelineFactory

3. UDPServerHandler

Ii. Client

1. UDPClient

2. UDPClientChannelPipelineFactory

3. UDPClientHandler

3. Obtain an available port number through ScanGetPort

I. Server Side

1. UDPServer

Initialize a ConnectionlessBootstrap, setPipelineFactory, and bind a port number. ScanGetPort is a tool class that gets an available port number and the source code is pasted at the end.

Package com. ls. udp. server; import java.net. inetSocketAddress; import java. util. concurrent. executors; import org. jboss. netty. bootstrap. connectionlessBootstrap; import org. jboss. netty. channel. socket. nio. niow.ramchannelfactory; import com. andy. server. util. scanGetPort; public class UDPServer {public final int PORT; public UDPServer (int port) {PORT = port;} private ConnectionlessBootstrap bootstrap; void start () {// init the bootstrap = new ConnectionlessBootstrap (new niow.ramchannelfactory (Executors. newCachedThreadPool (); bootstrap. setPipelineFactory (new UdpChannelPipelineFactory (); bootstrap. bind (new InetSocketAddress (PORT); System. out. println ("server start at:" + ":" + PORT);} public static void main (String [] args) {/** get an available port number */int port = new ScanGetPort (). getPot (8080); new UDPServer (port ). start ();}}

2. UdpChannelPipelineFactory

Register a handler

package com.ls.udp.server;import org.jboss.netty.channel.ChannelPipeline;import org.jboss.netty.channel.ChannelPipelineFactory;import org.jboss.netty.channel.Channels;public class UdpChannelPipelineFactory implements ChannelPipelineFactory{        /**     * set the channel pipeline     *      */    @Override    public ChannelPipeline getPipeline() throws Exception {        ChannelPipeline pipeline = Channels.pipeline();        pipeline.addLast("handler", new UDPServerHandler());        return pipeline;    }}

3. UDPServerHandler

Handler class

Package com. ls. udp. server; import org. jboss. netty. buffer. channelBuffer; import org. jboss. netty. buffer. dynamicChannelBuffer; import org. jboss. netty. channel. channelHandlerContext; import org. jboss. netty. channel. exceptionEvent; import org. jboss. netty. channel. messageEvent; import org. jboss. netty. channel. simpleChannelUpstreamHandler; public class UDPServerHandler extends SimpleChannelUpstreamHandler {/*** for C HannelHandler, * is the core difference between UDP and TCP. * We All Know That UDP is connectionless. * That is to say, you get the current session connection through the getChannel () method of the MessageEvent parameter object. * but its isConnected () always returns false. * In UDP development, in the message retrieval Event Callback method, * after obtaining the current session connection channel object, you can directly send data to the peer channel through the channel write method. write (message, remoteAddress), * the first parameter is still the message object to be sent, * the second parameter is the peer SocketAddress object to be sent. * The most important thing to note here is SocketAddress. In TCP communication, we can use channel. getRemoteAddress (), * but in UDP communication, we must obtain the SocketAddress address of the Peer end by calling the getRemoteAddress () method in MessageEvent. * // @ Override public void messageReceived (ChannelHandlerContext ctx, MessageEvent e) throws Exception {ChannelBuffer buffer = (ChannelBuffer) e. getMessage (); byte [] recByte = buffer. copy (). toByteBuffer (). array (); String msg = new String (recByte); System. out. println ("from client:" + msg); ChannelBuffer responseBuffer = new DynamicChannelBuffer (1); responseBuffer. writeBytes ("". getBytes (); // write to the client e. getChannel (). write (responseBuffer, e. getRemoteAddress (); super. messageReceived (ctx, e) ;}@ Override public void exceptionCaught (ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {super. predictioncaught (ctx, e );}}

Ii. Client

(The basic structure is similar to that on the server side. I will not repeat it here)

1. UDPClient

package com.ls.udp.client;import java.net.InetSocketAddress;import java.util.Scanner;import org.jboss.netty.bootstrap.ConnectionlessBootstrap;import org.jboss.netty.buffer.ChannelBuffer;import org.jboss.netty.buffer.DynamicChannelBuffer;import org.jboss.netty.channel.Channel;import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;public class UDPClient {    private ConnectionlessBootstrap  bootstrap;    private Channel channel;    public void start(){        //init the bootstrap        bootstrap=new ConnectionlessBootstrap(new NioDatagramChannelFactory());        bootstrap.setPipelineFactory(new UDPClientChannelPipelineFactory());        bootstrap.setOption("localAddress", new InetSocketAddress(10001));        channel=bootstrap.bind();    }        public void writebytes(byte[] bt,InetSocketAddress isa){        if(bootstrap==null){            this.start();        }        ChannelBuffer responseBuffer= new DynamicChannelBuffer(12);                responseBuffer.writeBytes(bt);        channel.write(responseBuffer, isa);    }            public static void main(String[] args) {                        UDPClient uClient=new UDPClient();                        Scanner scanner=new Scanner(System.in);        String lienString=scanner.nextLine();        while(!lienString.equals("bye")){                        uClient.writebytes(lienString.getBytes(), new InetSocketAddress("192.168.1.107",8080));            lienString=scanner.nextLine();        }    }        }

 

 

 

2. UDPClientChannelPipelineFactory

 

package com.ls.udp.client;import org.jboss.netty.channel.ChannelPipeline;import org.jboss.netty.channel.ChannelPipelineFactory;import org.jboss.netty.channel.Channels;public class UDPClientChannelPipelineFactory implements ChannelPipelineFactory{        /**     * set the channel pipeline     *      */    @Override    public ChannelPipeline getPipeline() throws Exception {        ChannelPipeline pipeline = Channels.pipeline();        pipeline.addLast("handler", new UDPClientHandler());        return pipeline;    }}

 

 

3. UDPClientHandler

 

package com.ls.udp.client;import org.jboss.netty.buffer.ChannelBuffer;import org.jboss.netty.channel.ChannelHandlerContext;import org.jboss.netty.channel.ExceptionEvent;import org.jboss.netty.channel.MessageEvent;import org.jboss.netty.channel.SimpleChannelUpstreamHandler;public class UDPClientHandler extends SimpleChannelUpstreamHandler{    @Override    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)            throws Exception {                        ChannelBuffer buffer = (ChannelBuffer)e.getMessage();        byte[] recByte=buffer.copy().toByteBuffer().array();                String msg=new String(recByte);        System.out.println("from server:"+msg);                        super.messageReceived(ctx, e);    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)            throws Exception {        super.exceptionCaught(ctx, e);    }    }

3. Obtain an available port number through ScanGetPort

package com.andy.server.util;import java.io.IOException;import java.net.ServerSocket;/** * get the port * @author red * */public class ScanGetPort {    public synchronized  int  getPot(int first){        for(int i=first;i<65535;++i){            ServerSocket ss=null;            try {                 ss= new ServerSocket(i);            } catch (IOException e) {                //e.printStackTrace();            }finally{                if(ss!=null){                    if(ss.isBound()){                        try {                            ss.close();                            System.out.println(i);                            return i;                        } catch (IOException e) {                            e.printStackTrace();                        }                                            }                }            }        }        return -1;    }}

What is the difference between interfaces provided by netty webservice servlets?

Netty provides asynchronous, event-driven network application frameworks and tools to quickly develop high-performance, high-reliability network servers and client programs. That is to say, Netty is a NIO-based client and server-side programming framework. Using Netty ensures that you can quickly and easily develop a network application, such as a customer who implements a certain protocol, server applications. Netty simplifies and streamlined the programming and development process of network applications, such as TCP and UDP socket service development.
Netty is a NIO-based server (simplified socket development of TCP/UDP ).
Java writes that Web Services are online application Services released by enterprises to meet their specific business needs. Other companies or application software can access and use this online service over the Internet. In fact, the main goal of WebService is cross-platform interoperability. To achieve this goal, WebService is fully based on XML (Extensible Markup Language), XSD (XMLSchema), and other standards independent of the platform and software vendors, is a new platform for creating interoperable and distributed applications. From this we can see that in the following three cases, using WebService will bring great benefits.
Third-party services (such as http and tcp) are provided ).
Servlet: A small application executed by the server. It is a server component. For example, HttpServlet is used to process Http requests, accept requests, and dynamically generate responses.
The three have different concerns:
Netty provides a NIO-Based Server framework (simplified socket development of TCP/UDP), similar to mina. For example, implement a web server.
Web services focus on web services and establish a set of rules to enable cross-platform/cross-application Coco access. Such as the weather forecast interface and google Map interface.


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.