UDP protocol Development

Source: Internet
Author: User
Tags file transfer protocol

UDP is the short name of user Datagram protocol,udp, whose main function is to compress the network data traffic into the form of datagram, and provide a simple information delivery service oriented to transaction. Unlike the TCP protocol, the UDP protocol uses the IP protocol to transmit UDP datagram directly, and UDP provides a non-connected and unreliable datagram delivery service. When transmitting information using the UDP protocol, the user application must be responsible for resolving problems such as data loss, duplication, sequencing, error confirmation, etc. Because UDP has the advantage of small resource consumption and fast processing speed, it usually uses UDP for data transmission with low reliability such as video and audio, even if there is a certain packet loss rate, it will not seriously affect the function.

Introduction to UDP protocol

UDP is not connected, and both sides of the communication do not need to establish physical link connections. It is used in the network to process packets, and in the OSI model, it is in the fourth layer of transport, which is located on the upper layer of the IP protocol. It does not group, assemble, check, and sort datagrams, and is therefore unreliable. The sender of the message does not know whether the message was properly received by the other party.

UDP datagram format has header and data two parts, the header is simple, 8 bytes, including the following sections:

(1) Source ports: Source port number, 2 bytes, maximum value is 65535;

(2) Destination port: Destination number, 2 bytes, maximum value is 65535;

(3) Length: 2 bytes, the total length of the UDP user datagram;

(4) Checksum: 2 bytes for verifying the number segment of the UDP datagram and the "pseudo header" that contains the header of the UDP datagram. The checksum method is similar to the first checksum in the IP packet header.

Pseudo-header, also known as pseudo-header (Pseudo header): Refers to the TCP fragment or UDP datagram format, in front of the datagram header to increase the source IP address, destination IP address, IP packet Protocol field, TCP or UDP datagram total length, etc., a total of 12 bytes, The extension header structure that is formed. This pseudo-header is a temporary structure that does not move up or down, just to ensure that the socket is verified to be correct.

UDP Protocol Datagram Format:

The features of the UDP protocol are as follows.

(1) UDP does not establish a connection with the other party before transmitting the data, that is, UDP is not connected. Before transmitting the data, the sender and the receiver exchange information with each other to synchronize the two parties;

(2) UDP docking received the datagram does not send a confirmation signal, the sender does not know whether the data is received correctly, will not resend the data;

(3) UDP transmits data faster than TCP, the system overhead is also low: UDP is relatively simple, the UDP header contains the source port, destination port, message length and checksum and other small bytes. Because UDP is simpler and more flexible than TCP, it is often used for data transmission with low reliability, such as video, picture and Simple File transfer system (TFTP). TCP is suitable for applications with high reliability requirements but low real-time requirements, such as File Transfer Protocol FTP, Hypertext Transfer Protocol HTTP, Simple Mail Transfer Protocol SMTP, and so on.

Server-Side development

ImportIo.netty.bootstrap.Bootstrap;Importio.netty.channel.ChannelOption;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.nio.NioDatagramChannel; Public classChineseproverbserver { Public voidRunintPortthrowsException {eventloopgroup Group=NewNioeventloopgroup (); Try{Bootstrap b=NewBootstrap (); //with UDP communication, you need to create a channel by Niodatagramchannel when you create itB.group (Group). Channel (Niodatagramchannel.class)                    //the socket parameter is then set to support broadcast,. Option (Channeloption.so_broadcast,true)                    //finally set up the business processing handler. //compared to TCP communication, UDP does not have the actual connection between the client and the server.//Therefore, you do not need to set the handler for the connection (channelpipeline).//for the service side, you only need to set the handler of the boot helper class. . Handler (NewChineseproverbserverhandler ());        B.bind (port). Sync (). Channel (). Closefuture (). await (); } finally{group.shutdowngracefully (); }    }     Public Static voidMain (string[] args)throwsException {intPort = 8080; if(Args.length > 0) {            Try{Port= Integer.parseint (args[0]); } Catch(NumberFormatException e) {e.printstacktrace (); }        }        NewChineseproverbserver (). Run (port); }}Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.SimpleChannelInboundHandler;ImportIo.netty.channel.socket.DatagramPacket;ImportIo.netty.util.CharsetUtil;ImportIo.netty.util.internal.ThreadLocalRandom; Public classChineseproverbserverhandlerextendsSimplechannelinboundhandler {//Proverb List    Private Static FinalString[] DICTIONARY = {"As long as the Kung fu is deep, the iron bar grinds into needles. ",            "Old King Xie Tang ago Yan, flew into the ordinary people's home." "," Luoyang relatives and friends such as asked, character in the Jade pot. "," Time is money, cornucopia. ",            "Laojifuli, Costraint. Zhuangxin in the twilight of the martyrs! "}; PrivateString nextquote () {//due to the possibility of multithreading concurrent operation in Chineseproverbserverhandler,//so the thread-safe random class threadlocalrandom of Netty is used. //If you are using JDK7, you can use the JDK7 java.util.concurrent.ThreadLocalRandom directly.         intQuoteid =threadlocalrandom.current (). Nextint (Dictionary.length); returnDictionary[quoteid]; } @Override Public voidMessagereceived (Channelhandlercontext ctx, Object msg)throwsException {//Netty UDP is encapsulated so that it receives the Io.netty. Channel.socket.DatagramPacket object after the Netty encapsulation. Datagrampacket packet =(Datagrampacket) msg; //converts the packet content to a string (using the ToString (Charset) method of Bytebuf),String req =packet.content (). toString (Charsetutil.utf_8);        SYSTEM.OUT.PRINTLN (req); //The request message is then judged to be legitimate: if it is a "proverb dictionary query?", the construction reply message is returned. //Datagrampacket has two parameters: the first is to send the content, for the bytebuf;//The other is the destination address, including the IP and port, which can be obtained directly from the sent message datagrampacket.         if("Proverb dictionary query?"). Equals (req)) {Ctx.writeandflush (NewDatagrampacket (Unpooled.copiedbuffer ("Proverb Query Result:" +nextquote (), charsetutil.utf_8), Packet.sender ())); }} @Override Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {ctx.close ();    Cause.printstacktrace (); }}
Client Development

The client and server code of the UDP program are very similar, the only difference is that the UDP client constructs the request message, broadcasts the request message to all hosts within the network segment, and, for the server, receives the broadcast request message and sends it to the initiator of the broadcast message.

ImportIo.netty.bootstrap.Bootstrap;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.Channel;Importio.netty.channel.ChannelOption;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.DatagramPacket;ImportIo.netty.channel.socket.nio.NioDatagramChannel;ImportIo.netty.util.CharsetUtil;Importjava.net.InetSocketAddress; Public classchineseproverbclient { Public voidRunintPortthrowsException {eventloopgroup Group=NewNioeventloopgroup (); Try{Bootstrap b=NewBootstrap (); //creating UDP channel and setting support broadcast properties are exactly the same as the server. //due to the need not to establish a link with the server, after the UDP channel creation is completed, the client will send the broadcast message actively;//The most significant difference is that the TCP client sends a message to the client's business handler after the client and server link have been established successfully. B.group (Group). Channel (Niodatagramchannel.class). Option (Channeloption.so_broadcast,true). Handler (NewChineseproverbclienthandler ()); Channel CH= B.bind (0). Sync (). Channel (); //broadcast UDP messages to all machines in a network segment//used to construct datagrampacket to send broadcast messages,//Note that the IP of the broadcast message is set to "255.255.255.255". //after the message is broadcast, the client waits for 15s to receive the service-side reply message, and then exits and frees the resource. Ch.writeandflush (NewDatagrampacket (Unpooled.copiedbuffer ("Proverb dictionary query?"), Charsetutil.utf_8),NewInetsocketaddress ("255.255.255.255", Port))            ). sync (); if(!ch.closefuture (). Await (15000) {System.out.println ("Query timed out!"); }        } finally{group.shutdowngracefully (); }    }     Public Static voidMain (string[] args)throwsException {intPort = 8080; if(Args.length > 0) {            Try{Port= Integer.parseint (args[0]); } Catch(NumberFormatException e) {e.printstacktrace (); }        }        Newchineseproverbclient (). Run (port); }}ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.SimpleChannelInboundHandler;ImportIo.netty.channel.socket.DatagramPacket;ImportIo.netty.util.CharsetUtil; Public classChineseproverbclienthandlerextendsSimplechannelinboundhandler {@Override Public voidmessagereceived (Channelhandlercontext ctx, Object o)throwsException {//after receiving a message from the server, turn it into a string and then decide whether to start with a "Proverb query result:"//if no problems such as packet loss occur, the data is complete, the query results are printed, and the resource is freed. Datagrampacket msg =(Datagrampacket) o; String Response=msg.content (). toString (Charsetutil.utf_8); if(Response.startswith ("Proverb Query Result:") {System.out.println (response);        Ctx.close (); }} @Override Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {cause.printstacktrace ();    Ctx.close (); }}

UDP protocol Development

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.