1.UDP Introduction
Send a message using UDP, the other party does not necessarily receive, because all the information is sent in the form of a datagram, which requires the client to always wait for the message sent by the receiving server, Use the Datagramsocket class and the Datagrampacket class in Java to complete the development of a UDP program.
2. Program implementation
Use the Datagrampacket class to wrap a message that you want to send, and then use the Datagramsocket class to complete the send operation of the information. Common methods of the Datagrampacket class:
Type |
Method |
Describe
|
Structure |
DatagramPacket(byte[] buf, int length)
|
Constructed to DatagramPacket receive packets of length length . |
Structure |
DatagramPacket(byte[] buf, int length, InetAddress address, int port) |
Constructs a datagram package that is used to length send a package of length to a specified port number on a specified host. |
Byte[] |
getData() |
Returns the data buffer. |
int |
getLength()
|
Returns the length of the data that will be sent or received. |
Common methods of the Datagramsocket class:
Type |
Method |
Describe |
Structure |
DatagramSocket(int port) |
Creates a datagram socket and binds it to the specified port on the local host. |
void |
send(DatagramPacket p)
|
Sends a datagram packet from this socket. |
void |
receive(DatagramPacket p)
|
Receives a datagram packet from this socket. |
Server-side:
Packageorg.demo.net;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classUdpserver { Public Static voidMain (string[] args)throwsexception{datagramsocket DS=NULL; Datagrampacket DP=NULL; DS=NewDatagramsocket (3000); String Str= "Hello"; DP=NewDatagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 9000); System.out.println ("Send a message. "); Ds.send (DP); Ds.close (); }}
Operation Result:
Client:
Packageorg.demo.net;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket; Public classUdpClient { Public Static voidMain (string[] args)throwsexception{datagramsocket DS=NULL; byte[] buf =New byte[1024];//defines a byte array to receive dataDatagrampacket DP =NULL; DS=NewDatagramsocket (9000); DP=NewDatagrampacket (buf,1024); System.out.println ("Wait for data to be received. "); Ds.receive (DP); String Str=NewString (Dp.getdata (), 0,dp.getlength ()) + "from" +dp.getaddress (). Gethostaddress () + ":" +Dp.getport (); System.out.println (str); Ds.close (); }}
Operation Result:
UDP Programming of Java Network program