栗子:TestUDPServer.java
服务器端:
package com.zhj.www;import java.net.DatagramPacket;
import java.net.DatagramSocket;public class TestUDPServer {public static void main(String[] args)throws Exception {byte buf[] = new byte[1024];DatagramPacket dPacket = new DatagramPacket(buf, buf.length);DatagramSocket dSocket = new DatagramSocket(5678);while(true) {dSocket.receive(dPacket);System.out.println(new String(buf,0,dPacket.getLength()));;}}
}
客户端:
package com.zhj.www;import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;public class TestUDPClient {public static void main(String[] args) throws Exception{byte[] buf = (new String("Hello")).getBytes();DatagramPacket dPacket = new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",5678));DatagramSocket dSocket = new DatagramSocket(9999);dSocket.send(dPacket);dSocket.close();}
}
栗子2: