Use UDP to make a chat

Before making a UDP chat device, we need to add some knowledge. First, let's understand what UDP is:

What is UDP?
            The full name of UDP is User Datagram Protocol. Chinese is User Datagram Protocol. It is a connectionless transport layer protocol in the Internet protocol set, providing simple and unreliable transaction-oriented transmission services. Simply put, it is a transport protocol at the transport layer. There is no need to establish a connection in advance like TCP before transmission. If TCP is compared to "" "phone mode", then UDP can be compared to "writing mode".
  
We have a general understanding of the definition of UDP, then let's take a look at the characteristics of the "write letter mode":
   1. Unreliability:
      UDP uses the best efforts to deliver, but does not guarantee the success of delivery. In other words, the integrity and reachability of data transmitted through the udp protocol cannot be guaranteed. Therefore, the host does not need to maintain complex connection relationships. In layman's terms, the envelope you mail out may be lost on the way.
 2. No connectivity:
      udp is no connection, that is, there is no need to create a connection when communicating, and the transport layer of the target host does not give a confirmation after receiving it. Give an example that is not very appropriate: When you write a letter, you should not say hello to the other party in advance.
3. Message-oriented:
      do not modify the messages coming down from the application layer and the messages handed over to the ip network layer, directly add/remove the header and proceed to the next step. If the message is too long, it will be fragmented at the ip layer; if the message is too short, the header of the datagram at the ip layer will be very long. Nowadays, there are some post offices that provide full service, that is, as long as you buy stamps at this office, you only need to submit the content to be mailed when writing a letter. All the rest will be handled by the post office.
4. No congestion mechanism:
      The transmission rate of the source host will not be reduced after network congestion, which is very important for some real-time applications. Such as IP phone, real-time video, etc. At the same time, it is allowed to lose some data in network congestion, but it is not allowed to have too much data delay. For example, you have received a lot of envelopes, but at this time someone still needs to send you a letter, he will send the letter as usual, and will not stop his activities because you have received a lot of letters.
5. The
      sender of the client and server without a clear sense can also receive letters, and the recipient can also send letters.
6. Support one-to-one, one-to-many, many-to-one, many-to-many interactive communication
7. The header overhead is small, only 8 bytes,
is there a sudden question, what is the header? Don't worry, let's take a look at the composition of UDP and you will understand!
UDP consists of two parts, one is the header field , and the other is the data field . Here only introduce the header field: the
header field is only 8 bytes, divided into 4 fields:
  source port:  source port number. Choose when you need the other party to reply, and use all 0 when you don’t need it.
  Destination port: destination port number. Used at the end of delivery.
  Length: The length of the   udp user datagram, the minimum value is 8 (only the header).
  Checksum : Check whether there is any error in the transmission of udp user datagram, and discard it if there is an error.
In addition, we also need to know a little bit about ip and port:   What is an
IP address
?
    ip is equivalent to "mobile phone number", used to mark a computer on the network, such as 192.168.1.1. It is unique in the local area network. Each IP address consists of two parts: network number (marked with network address) and host number (marked with host address). There are five types of ABCDE.
  How to check IP?
            liunx terminal command

ifconfig

           Windows cmd command

ipconfig

  IP classification
      I Pv4 and IP6
          ipv4 are composed of four groups of numbers, and each group of numbers must be between 0 and 255. In other words, there are 256**3 ipv4 addresses in total.
         
Port (port)
  What is a port?
     Ports are used to mark applications on the host. Each application has a different
  port number. There are two types of port numbers :
     well known ports: well known ports
        , ranging from 0 to 1023. For example, the HTTP port number is 80 and the FTP port number is 21.
      Dynamic ports (Dynamic ports):
         When the program needs network communication, the host will allocate a port to the program from the available ports, that is, dynamic allocation. The port number is released at the same time when the program ends. The dynamic port number ranges from 1024 to 65535.

Finally, let's take a look at sockets:

What is socket (socket)?
        Socket is a way of process communication, which can realize process communication between different hosts. At present, most services on the network are based on socket to complete communication.

OK, then we are going to enter the topic and start writing the chat machine.

First of all, let's sort out the process:

1. Create a socket object

2. Binding local information

4. Send data

5. Receive and process data

6. Print data

7. Close the socket object

 

1. Import the socket module

import socket

2. Create a socket object

udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

note:

The socket requires two parameters when creating a socket: socket(AddressFamily,Type)

AdressFamily : You can choose AF_INET (for communication between Internet processes) or AF_UNIX (communication between processes on the same machine). In practice, AF_INET
Type : SOCK_STREAM (streaming socket, mainly used for TCP protocol) or SOCK_DGRAM (datagram) Socket, mainly using UDP protocol).

Here we need network communication and use udp protocol, so the two parameters are AF_INET and SOCK_DGRAM.

3. Binding local information

local_adress = ("",1314)
udp_socket.bind(local_adress)

Use the bind() method to bind the local information of the socket object. A tuple parameter is required. The tuple contains two elements. The first element is the ip address of the string type, and the second element is the integer. Port number (set by yourself, but must be greater than 1023, that is, use one of the dynamic ports).

4. Send data

dest_ip = input("请输入对方IP:")
dest_port = int(input("请输入对方端口号:"))
send_data = input("请输入内容:")
udp_socket.sendto(send_data.encode("ASCII"),(dest_ip,dest_port))

The socket calls the sendto() method on the object to send data, and the sendto() method requires two parameters. The first parameter is the data to be sent (note the need for transcoding); the second is a tuple type parameter with two elements: the first element is the ip of the target host, and the second element is the target host's The port number. Note that dest_port uses int conversion because the port number must be an integer.

5. Receive and process data

recv_data = udp_socket.recvfrom(1024)
recv_msg =recv_data[0].decode("ASCII")
recv_adress = recv_data[1]

Use the recvfrom() method to receive data. The received data is a tuple type with two elements: the first is the received content, and the second is a tuple (ip and port). At this time, recv_data is a tuple type. You can use the index to read its internal content separately, or you can use the unpacking method to receive data from recvfrom(). The first method used here. In addition, the received content needs to be decoded.

6. Print data

 print("来自【%s】的数据:\n%s" % (str(recv_adress),recv_msg))

%s is a character type, and recv_adress is a tuple type, so it needs to be type converted.

7. Close the socket object

udp_socket.close()

The complete code is as follows:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 15 20:38:15 2020

@author: x
"""
import socket

def sending_data(udp_socket):
     dest_ip = input("请输入对方IP:")
     dest_port = int(input("请输入对方端口号:"))
     send_data = input("请输入内容:")
     udp_socket.sendto(send_data.encode("ASCII"),(dest_ip,dest_port))


def recving_data(udp_socket):
    recv_data = udp_socket.recvfrom(1024)
    recv_msg =recv_data[0].decode("ASCII")
    recv_adress = recv_data[1]
    
    return recv_msg,recv_adress
    
    
def main():
    # 1.创建套接字对象
    udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    
    # 2.绑定本地信息
    local_adress = ("",1314)
    udp_socket.bind(local_adress)
    
    while True:
        # 3.发送数据
        sending_data(udp_socket)
       
        # 4.接收并处理数据
        recv_msg,recv_adress = recving_data(udp_socket)
        
        # 5.打印数据
        print("来自【%s】的数据:\n%s" % (str(recv_adress),recv_msg))
        
    # 6. 关闭套接字
    udp_socket.close()
    
if __name__ == "__main__":
    main()

Follow me and show you python!

Guess you like

Origin blog.csdn.net/qq_45807032/article/details/104937087