客户端 发送
package cn.usts.edu.lesson04;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket();
String msg = "hello udp application";
int port=9999;
InetAddress IP = InetAddress.getByName("127.0.0.1");
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),msg.getBytes().length,IP,port);
socket.send(datagramPacket);
socket.close();
}
}
服务端 接收
package cn.usts.edu.lesson04;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9999);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(), 0, packet.getLength()));
socket.close();
}
}
|