UDP does not specifically provide a server-side API as TCP does, all with Datagramsocket and packet datagrams. So UDP is connectionless, because all the links are in the datagram, let Datagramsocket to send.
Server End:
Import Java.net.DatagramPacket; Import Java.net.DatagramSocket; /** * @author wangking e-mail:admin717@gmail.com * @version Date Created: 2009-9-16 03:25:29 * Class Description */public class Udpserver {/* * * @param args */public static void main (string[] args) throws Exception {byte[] buf = new byte[1024]; Datagramsocket socket = new Datagramsocket (5678); Datagrampacket packet = new Datagrampacket (buf,buf.length); while (true) {socket.receive (packet); System.out.println (New String (buf,0,buf.length)); } } }
Client-side tests:
Import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;/** * @author Wangking e-mail:admin717@gmail.com * @version Date Created: 2009-9-16 03:30:11 * Class Description */public class UdpClient {public static VO ID Main (string[] args) throws Exception {datagramsocket socket = new Datagramsocket (9999); byte[] buf = "HHH". GetBytes (); Datagrampacket packet = new Datagrampacket (buf,0,buf.length,new inetsocketaddress ("127.0.0.1", 5678)); Socket.send (packet); Socket.close (); } }