java UDP传输

①:只要是网络传输,必须有socket 。

②:数据一定要封装到数据包中,数据包中包括目的地址、端口、数据等信息。

 

直接操作udp不可能,对于java语言应该将udp封装成对象,易于我们的使用,这个对象就是DatagramSocket. 封装了udp传输协议的socket对象。

 

因为数据包中包含的信息较多,为了操作这些信息方便,也一样会将其封装成对象。这个数据包对象就是:DatagramPacket.通过这个对象中的方法,就可以获取到数据包中的各种信息。

 

DatagramSocket具备发送和接受功能,在进行udp传输时,需要明确一个是发送端,一个是接收端。

 

udp的发送端:

①:建立udp的socket服务,创建对象时如果没有明确端口,系统会自动分配一个未被使用的端口。

②:明确要发送的具体数据。

③:将数据封装成了数据包。

④:用socket服务的send方法将数据包发送出去。

⑤:关闭资源。

 

udp的接收端:

①:创建udp的socket服务,必须要明确一个端口,作用在于,只有发送到这个端口的数据才是这个接收端可以处理的数据。

②:定义数据包,用于存储接收到数据。

③:通过socket服务的接收方法将收到的数据存储到数据包中。

④:通过数据包的方法获取数据包中的具体数据内容,比如ip、端口、数据等等。

⑤:关闭资源。

 

 

Eg:

发送端(客户端)

import java.net.*;

class  UdpSend{

        public static void main(String[] args)throws Exception {

                // 1,建立udp的socket服务。

                DatagramSocket ds = new DatagramSocket(8888);//指定发送端口,这个可以不指定,系统会随机分配。

                // 2,明确要发送的具体数据。

                String text = "udp传输演示 哥们来了";

                byte[] buf = text.getBytes();

                // 3,将数据封装成了数据包。

                DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("10.1.31.127"),10000);

                // 4,用socket服务的send方法将数据包发送出去。

                ds.send(dp);

                // 5,关闭资源。

                ds.close();

        }

}

 

接收端(服务器端)

 

import java.net.*;

class UdpRece {

        public static void main(String[] args) throws Exception{

                // 1,创建udp的socket服务。

                DatagramSocket ds = new DatagramSocket(10000);//必须指定,并且和上面的端口号一样!

                // 2,定义数据包,用于存储接收到数据。先定义字节数组,数据包会把数据存储到字节数组中。

                byte[] buf = new byte[1024];

                DatagramPacket dp = new DatagramPacket(buf,buf.length);

                // 3,通过socket服务的接收方法将收到的数据存储到数据包中。

                ds.receive(dp);//该方法是阻塞式方法。

                // 4,通过数据包的方法获取数据包中的具体数据内容,比如ip,端口,数据等等。

                String ip = dp.getAddress().getHostAddress();

                int port = dp.getPort();

                String text = new String(dp.getData(),0,dp.getLength());//将字节数组中的有效部分转成字符串。

                System.out.println(ip+":"+port+"--"+text);

                // 5,关闭资源。

                ds.close();

        }

}

 

 

练习:

通过键盘录入获取要发送的信息。

将发送和接收分别封装到两个线程中。

 

package july76net;

//一个聊天的例子,利用UDP传输协议

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

 

//客户端,发送端

class Send implements Runnable {

    private DatagramSocket ds;

 

    public Send(DatagramSocket ds) {

        super();

        this.ds = ds;

    }

 

    @Override

    public void run() {

        try {

            BufferedReader br = new BufferedReader(new InputStreamReader(

                    System.in));//数据源是键盘录入

            String line;

            while ((line = br.readLine()) != null) {

                byte[] buf = line.getBytes();

                DatagramPacket dp = new DatagramPacket(buf, buf.length,

                        InetAddress.getByName("localhost"), 10225);

 

                ds.send(dp);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

 

// 服务器端,接收端

class Rece implements Runnable {

    private DatagramSocket ds;

 

    public Rece(DatagramSocket ds) {

        super();

        this.ds = ds;

    }

 

    @Override

    public void run() {

        try {

            while (true) {

                byte[] buf = new byte[1024];

 

                DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);

                ds.receive(dp);

 

                String ip = dp.getAddress().getHostAddress();

                String data = new String(dp.getData(), 0, dp.getLength());

 

                System.out.println(ip + "     " + data);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

 

public class Demo6 {

    public static void main(String[] args) throws Exception {

        DatagramSocket sendDs = new DatagramSocket();

        DatagramSocket receDs = new DatagramSocket(10225);

        new Thread(new Send(sendDs)).start();

        new Thread(new Rece(receDs)).start();

    }

}

 

输出:

你好

127.0.0.1     你好

你好

127.0.0.1     你好

posted @ 2019-07-05 10:13  樊伟胜  阅读(1345)  评论(0编辑  收藏  举报