UDP通信(二)

package demo02;

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

public class UDPrecieve {
    public static void main(String[] args) throws IOException {
        //接收端
        //1.创建码头,绑定端口号
        DatagramSocket ds =new DatagramSocket(8000);
        //2.创建字节数组,接收发来的数据
        byte [] b =new byte [1024];
        while(true){
            //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 demo02;

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

public class UDPSend {

    public static void main(String[] args) throws IOException {
        // 发送端
        Scanner sc = new Scanner(System.in);
        // 1.创建数据包对象,封装要发送的数据,接收端的IP,接收端的接口
        InetAddress inet = InetAddress.getByName("192.168.1.172");
        // InetAddress inet =InetAddress.getLocalHost();//本机
        // 2.创建码头对象,进行数据包的发送
        DatagramSocket ds = new DatagramSocket();
        while (true) {
            System.out.println("请输入要传输的数据:");
            String mes = sc.nextLine();
            byte[] b = mes.getBytes();
            DatagramPacket dp = new DatagramPacket(b, b.length, inet, 8000);
            ds.send(dp);
        }
        // 3.关闭资源
        // ds.close();
    }

}

 

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