UDP不像TCP那樣專門提供了一個SERVER端API,所有的都用DatagramSocket,接受packet資料報。所以說UDP是不需連線的,因為所有的連結都是在資料報裡,讓DatagramSocket去發送。
Server端:
import java.net.DatagramPacket; import java.net.DatagramSocket; /** * @author wangking E-mail:admin717@gmail.com * @version 建立時間:2009-9-16 上午03:25:29 * 類說明 */ 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端的測試:
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; /** * @author wangking E-mail:admin717@gmail.com * @version 建立時間:2009-9-16 上午03:30:11 * 類說明 */ public class UDPClient { public static void 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(); } }