UDP transmission mode

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/dengyu810/article/details/102631361

UDP

Part of the investigation required documentation to learn, we need to understand the following two categories: the Java .net.DatagramSocket and java.net.DatagramPacket

java.net.DatagramSocket:

  • This class represents sockets for sending and receiving datagram packets. It's like during data transmission driver or pick-up members, as it guides the direction and place of arrival of transmission data transmitted
Construction method:
  • DatagramSocket () Constructs a datagram socket and bind it to any available port of the local host.

  • DatagramSocket (int port, InetAddress laddr) Creates a datagram socket, bound to the specified local address.

commonly used ways:
  • send (DatagramPacket p) data packets sent from this socket packet.

  • receive (DatagramPacket p) receiving a datagram packet from this socket.

  • close () Closes this datagram socket.

java.net.DatagramPacket:

  • This class represents a datagram packet. It is like a vehicle data transmission, that is, it carries the transfer of data between the host, the object data called packets, which not only encapsulates the data content, as well as the source data, the host sends an IP data ports and to a package so inside.
Construction method:
  • DatagramPacket (byte [] buf, int offset, int length, InetAddress address, int port)
    Constructs a datagram packet for length length offset to the offset of the specified port number packet is sent on the specified host.

  • DatagramPacket (byte [] buf, int length, InetAddress address, int port)
    Constructs a datagram packet for the length of the transmission to the specified port number on the specified host length packets.

  • DatagramPacket (byte [] buf, int length)
    configured DatagramPacket, for receiving packets of length length.

UDP receiving end

The first to write a UDP receiving end, probably thinking is, first through

DatagramSocket ds = new DatagramSocket(10003);

a new object that is used to send and receive data socket packet. Then

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

Defined packet, the last call to recieve the function receives the data, the data encapsulated in the packet.
It is noted that the sending device to the IP address and port of the receiving end must be IP and port corresponding to the host

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

public class UdpRecieve {
    public static void main(String[] args) throws IOException, IOException {

        System.out.println("udp  接收端......run");
        /**
         * 定义一个udp的接收端,接收发送过来的数据。并显示在屏幕上
         *
         * 思路:
         *     1、先有udp socket服务,就是先有插座。 而且记住:接收端一定要明确端口,否则,收不到数据
         *     2、接受数据。之前应该先将数据存储到数据包中。因为数据还有解析
         *     3、先定义数据包
         *     4、通过数据包对象获取数据包的内容,发送端的ip、发送端的端口、发送过来的数据
         *     5、关闭资源
         * */
        //1、先有udp socket服务,就是先有插座。而且记住:接收端一定要明确端口,否则,收不到数据
        DatagramSocket ds = new DatagramSocket(10000);

        //2、接受数据。之前应该先将数据存储到数据包中。因为数据还有解析
        //3、先定义数据包
        byte[] buf = new byte[1024];    //缓冲区,保存数据
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        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();
    }
}

Which is mounted in a while (true) loop, you can continue to receive data

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

public class UdpRecieve2 {
    public static void main(String[] args) throws IOException, IOException {
        System.out.println("udp  接收端     run");
        /**
         * 定义一个udp的接收端,接收发送过来的数据。并显示在屏幕上
         *
         * 思路:
         *     1、先有udp socket服务,就是先有插座。 而且记住:接收端一定要明确端口,否则,收不到数据
         *     2、接受数据。之前应该先将数据存储到数据包中。因为数据还有解析
         *     3、先定义数据包
         *     4、通过数据包对象获取数据包的内容,发送端的ip、发送端的端口、发送过来的数据
         *     5、关闭资源
         * */

        //1、先有udp  socket服务,就是先有插座嘛。而且记住:接收端一定要明确端口,否则,收不到数据
        DatagramSocket ds = new DatagramSocket(10000);

        while(true)
        {
            //2、接受数据。之前应该先将数据存储到数据包中。因为数据还有解析
            //3、先定义数据包
            byte[] buf = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buf, buf.length);
            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);
        }
    }
}

UDP sending end

With the following phrase to create a socket to guide the whereabouts of the data, the inside of the parameter "8888" represents the port of destination host is not sent, but the port to send the starting point, expressed sent out from the host of the 8888 port.

DatagramSocket ds = new DatagramSocket(8888);

Then use the following sentence data content, the transmission destination are packaged into such a packet inside, which represents a byte array buf parameter must be byte array is not a string array, the transmission is undoubtedly to buf.length length, InetAddress.getByName ( "127.255.25.1") is the host address of the destination, the meaning of the phrase by ip address acquired host address, destination 10000 indicates that the received data port, the port is to ensure that no other application occupancy.

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

Finally, to complete the send function calls to send

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

public class UdpSend {
    public static void main(String[] args) throws IOException, IOException {

        System.out.println("udp  发送端     run");

        /**
         * 通过查阅文档,了解到用于UDP传输协议的对象是DatagramSocket
         *
         * 通过UDP协议发送一段文本数据
         * 思路:
         *     1、需要先建立UDP的socket。它具备发送和接收功能
         *     2、将数据封装到数据包中。数据包对象是DatagramPacket
         *     3、使用socket对象的send方法将数据包发送出去
         *     4、关闭资源
         * */


        //1、需要先建立UDP的socket。它具备发送和接收功能
        DatagramSocket ds = new DatagramSocket(8888);

        //2、将数据封装到数据包中。数据包对象是DatagramPacket
        String text = "hello udp来了!";
        byte[] buf = text.getBytes();   //将数据转成字节数组
        //将字节数组封装到数据包中
        DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.255.25.1"), 10000);

        //3、使用socket对象的send方法将数据包发送出去
        ds.send(dp);

        //4、关闭资源
        ds.close();
    }
}

Send keyboard input data, in fact here is to add a keyboard entry, operation IO streams

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

public class UdpSend2 {
    public static void main(String[] args) throws IOException, IOException {

        System.out.println("udp  发送端     run");

        /**
         * 通过查阅文档,了解到用于UDP传输协议的对象是DatagramSocket
         *
         * 通过UDP协议发送一段文本数据 思路: 
         * 1、需要先建立UDP的socket。它具备发送和接收功能
         * 2、将数据封装到数据包中。数据包对象是DatagramPacket 
         * 3、使用socket对象的send方法将数据包发送出去
         * 4、关闭资源
         */

        // 1、需要先建立UDP的socket。它具备发送和接收功能
        DatagramSocket ds = new DatagramSocket(9999);

        // 2、将数据封装到数据包中。数据包对象是DatagramPacket。数据来自于键盘录入
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while ((line = bufr.readLine()) != null)
        {
            if("over".equals(line))
                break;
            byte[] buf = line.getBytes(); // 将数据转成字节数组
            // 将字节数组封装到数据包中
            DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.255.25.1"), 10000);
            ds.send(dp);
        }

        // 4、关闭资源
        ds.close();
    }
}

Success Example:

Before sending
Here Insert Picture description _www.wityx.com
from the keyboard input transmit content
Here Insert Picture description _www.wityx.com
receiving terminal
Here Insert Picture description _www.wityx.com

Guess you like

Origin blog.csdn.net/dengyu810/article/details/102631361