UDP发送端与接受端互动

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPSendTest {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        //创建一个发送端对象
        DatagramSocket ds=new DatagramSocket();
        String value="我是发送端发送的资源";
        byte[] buff=value.getBytes();
        InetAddress ip=InetAddress.getByName("172.27.35.1");
        DatagramPacket dp1=new DatagramPacket(buff, buff.length, ip, 1010);
        ds.send(dp1);
        //现在数据已经发送,开始接收数据
        DatagramPacket dp2=new DatagramPacket(new byte[1024],1024);
        //获取接收过来的数据
        ds.receive(dp2);
        byte[] re_value=dp2.getData();
        int re_length=dp2.getLength();
        System.out.println(new String(re_value,0,re_length));
        ds.close();
    }

}

你可能感兴趣的:(UDP发送端与接受端互动)