java中UDP编程
发送者类如下:
import java.net.*;
public class UdpSender {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
DatagramSocket ds = new DatagramSocket();
String info = "hello snooker 中国";
ds.send(new DatagramPacket(info.getBytes(), info.getBytes().length, InetAddress.getByName("127.0.0.1"), 3000));
ds.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:中文转换为byte时一个字符会转换成两个byte,所以DatagramPacket函数中长度参数不能用info.length()
接收者类如下:
import java.net.*;
public class UdpReceiver {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String info = new String(dp.getData(), 0, dp.getLength());
System.out.println(info + " from:" + dp.getAddress().getHostAddress() + ", port:" + dp.getPort());
ds.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行程序时必须先运行receiver类,否则数据会丢失
输出结果如下:
hello snooker 中国 from:127.0.0.1, port:64039

浙公网安备 33010602011771号