udp client send and receive data flow

1. Create a client socket to start communication. 
2. At this time, the server should be started first, and the communication can only be carried out when the ip and port number of the server are known.
3. There is no need to bind ip and port number locally. When using this socket object to send a message, the active port (1024-65535) will be automatically allocated.
Each restart of the program may be different each time.
4. Then encode the information to be sent, and then send the encoded bytecode to the specified server ip and port.
5. Message reception can also be performed here. To receive a message here, you must first send data to the specified server, and tell the server the client's ip and the port used.
6. If the message is blocked first, the message cannot be received. Here, the client does not need to bind the port. It can be understood that after the client sends the data to the server, the system silently binds
the client ip and port to the client in the background. fixed. In this way, the message sent by the server can be received by the client.
7. The received message also needs to be decoded. The decoding format corresponds to the encoding format of the data sent by the server, and the bytecode is converted into understandable data for printing.
8. Finally, the client udp socket is closed.
from socket import *
# client

# define client udp socket
socket_udp = socket (AF_INET, SOCK_DGRAM)
# Determine the target ip and port, here is the ip address of the server in the LAN and the port number bound to the server
dest_addr = (' #fill in the server ipv4 address here', 8989)

while True:
    # input send data
    temp_data = input('client:')
    # Add specific objects to form a dialogue form
    temp_data = 'client:' + temp_data
    # Encode the data to be sent, what encoding is used by the target address to decode and receive, and what encoding is used here to encode
    socket_data = temp_data.encode('gbk')
    # Call the function sendto() for udp sending data in the socket
    socket_udp.sendto(socket_data, dest_addr)
    # Prepare to receive data, the receive length is 1024
    temp_recv_data = socket_udp.recvfrom(1024)
    # Decode the received data
    socket_udp_recv_data = temp_recv_data[0].decode('gbk')
    # # Print the received message
    # print(socket_udp_recv_data, '\nThe port number used by the other party to send data is:', temp_recv_data[1][1])
    # print the received message
    print(socket_udp_recv_data)
# After sending, close the udp socket,
# socket_udp.close()

Guess you like

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