UDP是基于数据报文的传输协议,面向无连接,不可靠,下面介绍发送和接收的Demo:
发送程序:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.channels.DatagramChannel;
public class UDPSendDemo {
public static void main(String[] args) {
try {
//绑定端口,通过18651端口进行发送,也可以不绑定(有系统随机分配端口)
DatagramSocket ds = new DatagramSocket(18651);
DatagramPacket send = null;
try {
//获取键盘输入数据
BufferedReader input = new BufferedReader(
new InputStreamReader(System.in,"UTF-8"));
String buf = null;
try {
//检测到回车时,进行数据读取
while((buf = input.readLine())!=null){
//将字符串转换成字节数组
byte[] b = buf.getBytes("UTF-8");
//进行数据包封装,包含数据内容,长度,目的地址和目的端口
send = new DatagramPacket(
b,b.length,InetAddress.getLocalHost(),18650);
//发送
ds.send(send);
System.out.println("Send OK!");
if(buf.equals("886"))
break;
}
//关闭UDP
ds.close();
//关闭输入流
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
接收程序:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPReceiveDemo {
public static void main(String[] args) {
try {
//绑定端口,接收此端口收到的数据,这里一般是都要绑定的,不然有点傻X
DatagramSocket ds = new DatagramSocket(18651);
//定义接收缓冲区大小1024
byte[] buf = new byte[1024];
DatagramPacket rec = new DatagramPacket(buf,buf.length);
while(true){
try {
//在此等待外来数据
ds.receive(rec);
String msg = new String(rec.getData(),0,rec.getLength());
if(msg.equals("886")){
break;
}
String ip = rec.getAddress().getHostAddress();
int port = rec.getPort();
System.out.println(msg+" "+ip+":"+port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ds.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}