功能:

实现了单次一发一收:

import java.net.*;
import java.io.*;

public class udpRecv
{
    /*
    * 创建UDP传输的接收端
    * 1.建立udp socket服务,因为是要接收数据,必须指明端口号
    * 2,创建数据包,用于存储接收到的数据。方便用数据包对象的方法处理数据
    * 3,使用socket服务的receive方法将接收的数据存储到数据包中
    * 4,通过数据包的方法解析数据包中的数据
    * 5,关闭资源

    *抛一个大异常:IOException
    */
    public static void main(String[] args) throws IOException{
        //1,创建udp socket服务
        DatagramSocket ds = new DatagramSocket(10000);

        //2,创建数据包
        byte[] buf =new byte[1024];
        DatagramPacket dp =new DatagramPacket(buf,buf.length);

        //3,使用接收的方法将数据包存储到数据包中
        ds.receive(dp);//阻塞式

        //4.通过数据包对象的方法,解析其中的数据
        String ip = dp.getAddress().getHostAddress();
        int port  = dp.getPort();
        String content = new String(dp.getData(),0,dp.getLength());
        System.out.println(ip+"::" +port+":"+content);
        /*回发给手机数据*/
        //首先获取端口和地址
        InetAddress addr = dp.getAddress();
        String sendStr = "Hello ! 我是服务器";
        byte[] sendBuf;
        sendBuf = sendStr.getBytes("utf-8");//必须转换utf8,否则安卓显示乱码
        DatagramPacket sendPacket 
            = new DatagramPacket(sendBuf , sendBuf.length , addr , port );

        ds.send(sendPacket);
        //5关闭资源
        ds.close();

        
        
    }
}
udpRecv.java

相关文章: