Java udp协议进行传输数据

Java中对使用UDP协议进行传输的数据,使用DategramSocket和DatagramPacket两个类来进行处理,其实挺简单的,在这里进行一个学习之后的总结。

发送端的代码:

public class Send {

    public static void main(String[] args) throws IOException {
        DatagramSocket ds=new DatagramSocket();
        String s="你好,这里是客户端的数据";
        byte[] buf=s.getBytes(); 
        InetAddress address=InetAddress.getByName("192.168.13.42");
        DatagramPacket dp=new DatagramPacket(buf, buf.length, address, 10086); 
        ds.send(dp);
        ds.close();
    }

}

接受端的代码

package www.cn.ft;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
 * udp编程
 * 服务端
 * @author Administrator
 *
 */

public class Recive {

    public static void main(String[] args) throws IOException {
        while(true) {
        DatagramSocket ds=new DatagramSocket(10086);

        byte[] buf=new byte[1024];
        DatagramPacket dp=new DatagramPacket(buf, buf.length);

        ds.receive(dp);

        byte[] data = dp.getData();
        int length = dp.getLength();

        String message=new String(data,0,length);

        InetAddress address = dp.getAddress();
        String hostAddress = address.getHostAddress();

        System.out.println("客户端发过来的数据是:"+message+" "+"ip地址是:"+hostAddress);
        //  ds.close();
        }
    }

}

你可能感兴趣的:(Java,udp,Java)