udp server send and receive data process

1. Create a server socket to start communication. 
2. Bind the ip and port number so that the client can find the program.
3. Because there is more than one local network card, try not to write dead, generally use "" to represent all local network cards.
4. Next, start listening for messages through the bound ip and port, and set the maximum received 1024-byte message to prevent the file from being too large and occupying the network buffer area.
5. After receiving the message, the ip and port sent by the client are received at this time, and then the message can be sent back through this ip and port.
6. When receiving a message, first determine whether the encoding format of the client is utf-8 or gbk, and decode the bytecode into understandable data in the same way.
7. When sending back, first encode the data to be sent and convert it into the corresponding bytecode to send.
8. The last step is to close the server. Generally, it is not closed. Closing the software means closing the server.
9. When using threads, processes, and process pools, parallel message sending and receiving can be realized, and pseudo-parallel can be realized when coroutines are used. The principle is to switch between methods.
10. Coroutines can be operated using encapsulated frameworks, greenlet and gevent frameworks.
11. When the server loops for message blocking (receiving messages), unlike tcp, there is no need to reuse or release the bound port every time it is used.
12. After waving four times, tcp will wait for the client to release the port for about a minute. udp is a burst communication, which is received as soon as it comes, and then goes away after waving.
13. So there is no need to immediately reuse this port again here.
from socket import *
# Server

# Create server socket
socket_serve = socket (AF_INET, SOCK_DGRAM)
# Determine the local port, there may be multiple, so there is no limit
local_port = ('', 8989)
# bind local port
socket_serve.bind(local_port)

while True:
    # The local port listens for client data (receives data)
    socket_temp_serve_data = socket_serve.recvfrom(1024)
    # data decoding
    socket_serve_data = socket_temp_serve_data[0].decode('gbk')
    # print the received data
    print(socket_serve_data)
    # The user enters data and sends it to the client
    socket_serve_sendto_temp_data = input('Server:')
    #Encode the data entered by the user
    socket_serve_sendto_temp_data = '服务端:' + socket_serve_sendto_temp_data
    socket_serve_sendto_data = socket_serve_sendto_temp_data.encode('gbk')
    # transmit data to client
    socket_serve.sendto(socket_serve_sendto_data, socket_temp_serve_data[1])
# Close the socket server
# socket_serve.close()

  

Guess you like

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