Network programming foundation---UDP

       The last blog is mainly for this part of the service. Recently, I learned about the network programming part. It happened that the computer network also talked about ip addresses, so I made up for some knowledge of IP transmission. Now let's officially summarize the two transmission protocols UDP and TCP.

Protocols for network communication:

udp通讯协议

tcp通讯协议。

Three elements of network communication:
1. Source address and destination address of IP transmission
2. Port number.
3. Agreement.
write picture description here

    端口号是没有类描述的。
    端口号的范围: 0~6553501023,系统紧密绑定于一些服务。 
    1024~65535  我们可以使用....
    常用端口       
    HTTPS端口 :443  
  Telnet端口:23 (远程登录)
  HTTP端口:80 (超文本传输协议) 
  FTP 端口:21 (文件传输协议)
  DNS 端口:53 (域名服务系统)
  POP3端口:110(邮筒协议)
  SMTP端口:25 (简单邮件传输协议) 


The English meaning of Socket socket is "hole" or "socket". As the process communication mechanism of 4BDS UNIX, take the latter meaning. Also commonly referred to as a "socket" to describe an IP address and port, it is a handle (reference) to a communication chain.
Each socket is an application.
Note:
Different communication rules need to define different sockets.
UDP: DatagramSocket, DatagramPacket
TCP: ServerSocket, Socket

UDP:
In java, the network communication industry is called Socket (socket) communication, and both devices that require communication must have Socket installed.

Different protocols have different sockets (Socket), which
is equivalent to that the terminal has no addressing function but only transmits data packets.

The characteristics of the UDP communication protocol:
1. Encapsulate the data into data packets, oriented to no connection.
2. The size of each data packet is limited to 64K
3. Because there is no connection, it is unreliable
4. Because there is no need to establish a connection, so the speed is fast
5. udp communication is not divided between the server and the client, only the sender and the receiver end.

比如: 物管的对讲机, 飞Q聊天、 游戏... 
你知道为什么游戏的时候会莫名其妙卡死吗?
就是因为是用UDP来传输 导致数据包丢失 为什么用UDP 那是因为速度快响应快

Let's talk about it first:
InetAddress (IP class)

Commonly used methods:
getLocalHost(); Get the IP address of the machine
getByName("IP or host name") generates an IP address object according to the string form of an IP address or a host name. (used to obtain other people's IP address object) generally use IP address

getHostAddress() returns a string representation of an IP address.
getHostName() returns the hostname of the computer. (The host name can be modified)
getAllByName() returns all the IP addresses of the host. Some domain names correspond to multiple IP addresses
. For example, Baidu Baidu is a domain name but there are multiple servers behind it, which is a cluster mode.

InetAddress[] inetAddress=
InetAddress.getAllByName("www.baidu.com");
for(int i=0;i<inetAddress.length;i++)
System.out.println(inetAddress[i].getHostAddress());

输出:
119.75.213.61
119.75.216.20
    //getLocalHost 获取本机的IP地址对象
        /*InetAddress address = InetAddress.getLocalHost();
        System.out.println("IP地址:"+address.getHostAddress());
        System.out.println("主机名:"+address.getHostName());*/

        //获取别人机器的IP地址对象。


        //可以根据一个IP地址的字符串形式或者是一个主机名生成一个IP地址对象。
        InetAddress address = InetAddress.getByName("Jolly-pc140116");
        System.out.println("IP地址:"+address.getHostAddress());
        System.out.println("主机名:"+address.getHostName());



        InetAddress[]  arr = InetAddress.getAllByName("www.baidu.com");//域名

Socket under udp protocol (also called socket):

DatagramSocket(udp插座服务)
DatagramPacket(数据包类)
    DatagramPacket(buf, length, address, port)
    buf: 发送的数据内容
    length : 发送数据内容的大小。
    address : 发送的目的IP地址对象
    port : 端口号。

The use steps of the sender:
1. Establish a udp service.
2. Prepare the data, encapsulate the data into a data packet and send it. The data packet of the sender should carry the IP address and port number.
3. Call the udp service to send data.
4. Shut down the resource.

来看一下UDP两台电脑间是如何通信吧
//发送端
public class Demo1Sender {

    public static void main(String[] args) throws IOException {
        //建立udp的服务
        DatagramSocket datagramSocket = new DatagramSocket();
        //准备数据,把数据封装到数据包中。
        String data = "这个是我第一个udp的例子..";
        //创建了一个数据包
        DatagramPacket packet = new DatagramPacket(data.getBytes(), data.getBytes().length,InetAddress.getLocalHost() , 9090);
        //调用udp的服务发送数据包
        datagramSocket.send(packet);
        //关闭资源 ---实际上就是释放占用的端口号
        datagramSocket.close();

    }

}
//接收端
    //建立udp的服务 ,并且要监听一个端口。
        DatagramSocket  socket = new DatagramSocket(9090);

        //准备空的数据包用于存放数据。
        byte[] buf = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); // 1024
        //调用udp的服务接收数据
        socket.receive(datagramPacket); //receive是一个阻塞型的方法,没有接收到数据包之前会一直等待。 数据实际上就是存储到了byte的自己数组中了。
        System.out.println("接收端接收到的数据:"+ new String(buf,0,datagramPacket.getLength())); // getLength() 获取数据包存储了几个字节。
        //关闭资源
        socket.close();

Summary:
1. Open the receiver first and then open the sender, otherwise it will cause data loss
2. receive is a blocking method that will wait until a packet is received. The equivalent of sacnner is to wait for input, which means that the receiver will only go down if it receives data.
3. Note: When the data packet sends a string transmission, look carefully at the length of the sent bytes rather than the length of the string

//对的
 String data = "这个是我第一个udp的例子..";
DatagramPacket packet = new DatagramPacket(data.getBytes(),   
data.getBytes().length,InetAddress.getLocalHost() , 9090);
//错的 长度取字符串的长度了  显然长度要小于实际长度 就会数据丢失
 String data = "这个是我第一个udp的例子..";
DatagramPacket packet = new DatagramPacket(data.getBytes(),   
data.length,InetAddress.getLocalHost() , 9090);

4. The port number can be arbitrarily just an identifier, but it must be in the range such as 1024~65535. We can use it.... The port of the local server is generally set to 80. This is a digression.
5. In the udp protocol, there is an IP address called the broadcast address , the broadcast address is the host number 255 address. Only when udp has a broadcast address and TCP does not send a message to the broadcast IP address, all machines on the same network segment can receive the information.

Next, let's look at the UDP implementation of a group chat:

//群聊发送端
public class ChatSender extends Thread {

    @Override
    public void run() {
        try {
            //建立udp的服务
            DatagramSocket socket = new DatagramSocket();
            //准备数据,把数据封装到数据包中发送
            BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            DatagramPacket packet  = null;
            while((line = keyReader.readLine())!=null){
                //把数据封装 到数据数据包中,然后发送数据。
                packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("192.168.15.255"), 9090);
                //把数据发送出去
                socket.send(packet);
            }
            //关闭 资源
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
//群聊接收端
public class ChatReceive extends Thread {

    @Override
    public void run() {
        try {
            //建立udp的服务,要监听一个端口
            DatagramSocket socket = new DatagramSocket(9090);
            //准备空的数据包存储数据
            byte[] buf = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            boolean flag = true;
            while(flag){
                socket.receive(packet);
                // packet.getAddress() 获取对方数据 包的IP地址对象。
                System.out.println(packet.getAddress().getHostAddress()+"说:"+new String(buf,0,packet.getLength()));
            }
            //关闭资源
            socket.close();

        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}
//主函数
public class ChatMain {

    public static void main(String[] args) {
        ChatReceive chatReceive = new ChatReceive();
        chatReceive.start();

        ChatSender chatSender = new ChatSender();
        chatSender.start();


    }

}

output:
write picture description here

Summary: 1. The receiver cannot be opened repeatedly because the port is occupied. If the main function is started repeatedly, it is equivalent to listening to the port twice, and such an error will be reported.
write picture description here
2. When using multi-threading to operate the group chat, the while loop must have an exit condition Otherwise, you will get an error when you close the infinite loop, so you need to use the While+flag variable to control the exit (for details, see the multi-threaded interrupt I wrote before)
3. You cannot throw an exception when you operate a multi-threaded group chat. You can only use the Try catch exception because Thread is a thread that does not throw exceptions as a parent class and cannot throw exceptions as a subclass (specifically, the last summary of exceptions)

There is one more problem to pay attention to: this thing took me for a long time and then found the problem...
If you use UTF-8 to program the sender code and the other party is the default receiver code of GBK, it will transfer Chinese characters at this time. The garbled characters don't affect
it. How to
solve
it The format name.getBytes("utf-8") converts the name string into a byte array in utf-8 format
new String(name.getBytes("GBK"), "utf-8")) encodes byte in GBK format Converted to string in UTF-8 format

String name="我爱你";
        if(name.equals(new String(name.getBytes(),"utf-8"))) {
            System.out.println(name);
        }
}

Back in the group chat:

packet = new DatagramPacket(line.getBytes("GBK"), line.getBytes().length, InetAddress.getByName("192.168.15.255"), 9090);

This will report an error. Only in this way can we be unified.

packet = new DatagramPacket(line.getBytes("GBK"), line.getBytes("GBK").length, InetAddress.getByName("192.168.15.255"), 9090);

Group chat recipient: Either method works


String name=new String(datagramPacket.getData(),datagramPacket.getLength());
System.out.println(new String(buffer,0,datagramPacket.getLength()));都可以

The recipient can also get the sender's information
packet.getAddress().getHostAddress() to get the sender's ip address
packet.getAddress().getHostName() to get the sender's computer name (can be modified)

Digression:
When running the class file from the command line,
java needs to add the package name and it is java myjar.ww myjar in the bin directory is the package name

UDP is a connectionless protocol. The sender's port is randomly generated by the sender (according to different network environments, the sender's IP may also be randomly selected from the address pool). After sending, the IP + port is invalid. .

Note: The port that the sender sends data is random

Reference:
https://blog.csdn.net/napolun007/article/details/6050241
Various protocols

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325933202&siteId=291194637
Recommended