UDP通信(一)

package demo01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPrecieve {
    public static void main(String[] args) throws IOException {
        
        // 接收端(单线上传)b
        // 1.创建码头,绑定端口号
        DatagramSocket ds = new DatagramSocket(8000);
        // 2.创建字节数组,接收发来的数据
        byte[] b = new byte[1024];
        // 3.创建数据包对象
        DatagramPacket dp = new DatagramPacket(b, b.length);
        // 4.接收数据
        ds.receive(dp);
        // 5.拆包
        int len = dp.getLength();
        String ip = dp.getAddress().getHostAddress();
        int port = dp.getPort();
        System.out.println("ip:" + ip + "端口号:" + port + "内容:" + new String(b, 0, len));
        // 6.释放资源
        ds.close();
    }

}
package demo01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPSend {
    // 发送端(单线上传)
    public static void main(String[] args) throws IOException {
        // 1.创建数据包对象,封装要发送的数据,接收端的IP,接收端的接口
        byte[] b = "你好".getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        DatagramPacket dp = new DatagramPacket(b, b.length, inet, 8000);
        // 2.创建码头对象,进行数据包的发送
        DatagramSocket ds = new DatagramSocket();
        ds.send(dp);
        // 3.关闭资源
        ds.close();
    }

}

 

package demo01;
import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;
public class UDPrecieve {public static void main(String[] args) throws IOException {// 接收端(单线上传)b// 1.创建码头,绑定端口号DatagramSocket ds = new DatagramSocket(8000);// 2.创建字节数组,接收发来的数据byte[] b = new byte[1024];// 3.创建数据包对象DatagramPacket dp = new DatagramPacket(b, b.length);// 4.接收数据ds.receive(dp);// 5.拆包int len = dp.getLength();String ip = dp.getAddress().getHostAddress();int port = dp.getPort();System.out.println("ip:" + ip + "端口号:" + port + "内容:" + new String(b, 0, len));// 6.释放资源ds.close();}
}

 

posted @ 2018-07-02 11:59  淅沥沥丶下雨  阅读(77)  评论(0编辑  收藏  举报