网络编程--使用UDP发送接收数据

package com.zhangxueliang.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
 * 使用UDP协议发送接收数据
 * @author zxlt
 *
 */
public class SendDemo {

    public static void main(String[] args) throws IOException {
        //创建发送端socket对象
        DatagramSocket ds = new DatagramSocket();
        //创建数据并打包
        String s = "Hello udp222,Im coming";
        byte[] bys = s.getBytes();
        int length = bys.length;
        InetAddress address = InetAddress.getByName("zxlt");
        int port  = 8888;
        //打包
        DatagramPacket dp = new DatagramPacket(bys,length,address,port);
        //发送数据
        ds.send(dp);
        //释放资源
        ds.close();
    }

}

 

package com.zhangxueliang.udp;

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

public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        //创建接收端Socket对象
        DatagramSocket ds = new DatagramSocket(8888);
        //接收数据
        byte[] bys = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bys,bys.length);
        System.out.println(1);
        ds.receive(dp);//阻塞
        System.out.println(2);
        //解析数据
        InetAddress address = dp.getAddress();
        byte[] data = dp.getData();
        int length = dp.getLength();
        //输出数据
        System.out.println("sender--> "+address.getHostAddress());
        System.out.println(new String(bys,0,length));
        //释放资源
        ds.close();
    }
}

 

posted @ 2018-12-16 11:18  学亮编程手记  阅读(493)  评论(0编辑  收藏  举报