服务端;
import java.net.*;
public class TestUDPServer {
public static void main(String args[])throws Exception{
byte buf[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
DatagramSocket ds = new DatagramSocket(5678);
while(true){
ds.receive(dp);
System.out.println(new String(buf,0,dp.getLength()));
}
}
}
客户端;
import java.net.*;
public class TestUDPClient {
public static void main(String args[])throws Exception{
byte buf[] = (new String("hello")).getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.01",5678));
DatagramSocket ds = new DatagramSocket(9999);//本地端口号;
ds.send(dp);
ds.close();
}
}
运行结果;
hello