Earlier in the introduction of the TCP/IP protocol, we have mentioned that in the TCP/IP protocol Transport layer In addition to the TCP protocol has a UDP protocol, compared to the UDP application is not as broad as TCP, but with the development of computer network UDP protocol is increasingly showing its power, Especially in situations where there is a strong need for real-time interactivity, such as online games and video conferencing, UDP is extremely powerful.
UDP uses datagram (datagram) transmission, the packet is a best-effort way of transmitting data, it just records the destination of the data in the packet, and then directly on the network, the system does not guarantee that the data can arrive safely, or when it can be sent, it does not guarantee the quality of transmission.
Datagram (datagram) is a logical grouping format for transmitting information on a network layer data unit, which is a kind of message propagating in the network, independent and contains address information, which can reach the destination, arrival time, and whether the content will change when it arrives is not exactly known. Its communication parties do not need to establish a connection, and for some applications that do not require very high quality, datagram communication is a very good choice. There is a high real-time situation, such as in real-time audio and video applications, the loss of data packets and location is static, can be tolerated by people, then can be transmitted using the UDP protocol.
Datagramsocket (datagram sockets) work consists of 3 classes of information: Datagrampacket, Datagramsocket, and MulticastSocket. The Datagrampacket object depicts the datagram address information, Datagramsocket represents the client program and the Service Program report socket, and MulticastSocket depicts a datagram socket capable of multi-point transmission.
Example: A client/server program that leverages datagram communication
(1) First to set up a socket for datagram communication, we can implement it by creating a Datagramsocket object
(2) Create a datagram packet to implement a non-connected packet delivery service. Each packet is created with the Datagrampacket class, and the Datagrampacket object encapsulates the datagram packet data, packet length, destination address, and target interface
(3) After you create the Datagramsocket and Datagrampacket objects, you can send a datagram packet. The send is implemented by invoking the Send () method of the Datagramsocket object, which requires the Datagrampacket object as a parameter to emit the data that was just encapsulated in the Datagrampacket object into the datagram.
(4) In order to receive the result datagram packet returned from the server, we need to create a new Datagrampacket object, which calls for another way to construct the Datagrampacket datagrampacket (byte[] Buffer,int Length), that is, simply indicate the buffer and the lengths of the data to be stored. Call the Receive () method of the Datagramsocket object to complete the work of receiving datagrams, where the Datagrampacket object created above is used as a parameter, and the method blocks until a datagram packet is received.
(5) processing the data in the receiving buffer to obtain the service result
(6) When the communication is complete, you can use the close () method of the Datagramsocket object to close the datagram communication socket.
Here is a simple server program and client program that uses datagram communication, which can only complete simple communication with the server.
A, server-side programs
Package org.test.socket.server;import java.io.ioexception;import java.net.datagrampacket;import java.net.DatagramSocket;import java.net.SocketException;/** * @author administrator * */public class udpserver { public static void main (String[] args) { try { //Creating socket datagramsocket socket = new datagramsocket (12345); //creating a Receive package byte[] buf = new byte[1024]; DatagramPacket receivePacket = new Datagrampacket (BUF, BUF.LEngth); system.out.println ("Start receiving package ....") ; //Cycle Monitoring while (True) { socket.receive (Receivepacket); string name = receivepacket.getaddress (). toString (); system.out.println ("From Host:" + name + "\ n port:" +receivepacket.getport ()); &Nbsp; string s = new string ( Receivepacket.getdata (), 0,receivepacket.getlength ()); system.out.println ("Received data:" +s); } } catch ( Socketexception e) { // todo auto-generated catch block e.printstacktrace (); } catch (IOException e) { // TODO auto-generated catch block E.printstacktrace (); } }}
b, client programs
package org.test.socket;import java.io.ioexception;import java.net.datagrampacket;import java.net.datagramsocket;import java.net.inetaddress;import java.net.socketexception;import java.net.unknownhostexception;public class udpclient { public Static void main (String[] args) { try { // Creating socket DatagramSocket socket = new Datagramsocket (); //creating a Send package inetaddress host = inetaddress.getbyname ("localhost"); string msg = "Hello,i ' M client"; datagrampacket sendpacket = new datagrampacket ( Msg.getbytes (), msg.length (), host,12345); //Sending Data socket.send (Sendpacket); } catch (socketexception e) { // TODO Auto-generated catch block e.printstacktrace (); } catch (unknownhostexception e) { // todo auto-generated catch block e.printstacktrace (); } catch (IOException e) { // TODO auto-generated catch block E.printstacktrace (); } }}
C, the results of the operation:
Start receiving package .... From host:/127.0.0.1 Port: 51240 received data: Hello,i ' m client
D, this is only a demonstration of UDP communication mode, the above can also be changed to both sides of the communication
Multicast sockets MulticastSocket
Datagramsocket only allows datagrams to send a destination address, MulticastSocket allows datagrams to be broadcast to all customers on that port.
Multicast datagram sockets are used to send and receive IP multicast packets. MulticastSocket is a datagramsocket that has additional functionality for groups that join other multicast hosts on the Internet.
Multicast sockets and Client/server programs
Server-side programs.
Package org.test.socket.server;import java.io.ioexception;import java.net.datagrampacket;import java.net.InetAddress;import java.net.MulticastSocket;import java.net.UnknownHostException; Public class multiserver { public static void main (String [] args) { try { // TODO Create socket multicastsocket socket = new multicastsocket (12345); InetAddress group = Inetaddress.getbyname ("231.0.0.0"); Socket.joingroup (group); //Receiving datagrams for (int i = 0;i<100;i++) { byte[] buf = new byte[256]; datagrampacket receivepacket = new datagrampacket (buf, Buf.length); Socket.receive (Receivepacket); //Removing spaces Byte[] buf2 = new byte[receivepacket.getlength ()]; system.arraycopy (ReceivePacket.getData (), 0, buf2, 0, receivepacket.getlength ()); system.out.println (new string (BUF2)); } //Delete multicast address Socket.leavegroup (group); socket.close ( ); } catch (unknownhostexception e) { // todo auto-generated catch block e.printstacktrace (); } catch (ioexception e) { // TODO Auto-generated catch block e.printstacktrace (); } }}
Client Programs
package org.test.socket;import java.io.ioexception;import java.net.datagrampacket;import Java.net.inetaddress;import java.net.multicastsocket;import java.net.unknownhostexception;public class multiclient { public static void main (String[] args) { try { // Create socket multicastsocket socket = new multicastsocket (); inetaddress group = inetaddress.getbyname ("231.0.0.0"); //creating a Send packet byte[] buf = new byte[0]; Datagrampacket sendpacket = new datagrampacket (buf, 0, group, 12345); //Sending Data for (int i = 0;i < 5;i ++) { byte[] buf1 = ("Data line" + i). GetBytes (); Sendpacket.setdata (BUF1); sendpacket.setlength (buf1.length); &nbSp; socket.send (sendpacket); } socket.close (); } catch (unknownhostexception e) { // TODO Auto-generated catch block e.printstacktrace (); } catch (ioexception e) { // TODO Auto-generated catch block e.printstacktrace (); } }}
This article is from the "Ah Cool blog source" blog, please make sure to keep this source http://aku28907.blog.51cto.com/5668513/1782137
Fundamentals of Java Network Programming (III)---UDP-based programming