先介绍两个UDP相关的类
DatagramSocket 这个是UDP套接字,一般服务器端可以绑定一个本机端口,而客户端发送方则不需要。
DatagramPacket 这个是数据报包,服务器端直接按缓存读,客户端则需要指定Ip地址和端口
这次我们做个android手机端跟电脑端通信
电脑端:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpRecv {
public static void main(String[] args) throws Exception{
//绑定本机断开
DatagramSocket ds = new DatagramSocket(8080);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
//接收数据包
ds.receive(dp);
//取出数据报内容
String str = new String(dp.getData(),0,dp.getLength());
System.out.println(str);
//打印发送方的地址
System.out.println("ip:"+dp.getAddress().getHostAddress()+"port:"+dp.getPort());
ds.close();