On the client code first
Package Com.test.net;import Java.net.datagrampacket;import Java.net.datagramsocket;import java.net.InetAddress; public class UdpClient {/** *udp client */public static void main (string[] args) throws Exception {Datagramsocket socket=new D Atagramsocket (); String str= "Hello"; byte[] Buf=str.getbytes ();D atagrampacket packet=new datagrampacket (Buf,buf.length, Inetaddress.getbyname ("127.0.0.1"), 1111);/* Direct Contract */socket.send (packet);}}
Server-side code
Package Com.test.net;import Java.net.datagrampacket;import Java.net.datagramsocket;import java.net.InetAddress; Import Java.net.socketexception;public class Udpserver {/** *udp server */public static void main (string[] args) throws Except Ion {Datagramsocket socket=new datagramsocket (1111); byte[] Buf=new byte[256];D atagrampacket packet=new DatagramPacket (buf,buf.length);/* monitor, Block */socket.receive (packet); String Received=new string (Packet.getdata ()); System.out.println (Received);}}
First here to explain the UDP,UDP protocol is a non-connection protocol, simply speaking, is one-way send, do not need to establish a connection in advance, do not need to return the package. Therefore, only need an IP and port, UDP can be sent to this port, as to whether the IP and port, or the recipient does not receive, UDP is no matter. So the most important thing in UDP is two classes, one is Datagramsocket, the other is Datagrampacket, the first one is similar to socket, the second is UDP packet.
In the server, the receive method of the Datagrampacket is blocked, which is the equivalent of listening until the datagram is heard.
Output results
The result is that the server side outputs hello.
UDP interpretation of Java network programming