Network programming based on UDP protocol socket

1. UDP protocol introduction (datagram protocol)

  The UDP protocol is different from TCP. When communicating, it does not need to establish a two-way link in advance, and does not distinguish whether the client starts first or the server starts first. Working principle: Based on the information transmitted by the udp protocol, the protocol will automatically add custom data to the data. header, so that each data is a datagram, and the churn protocol produces sticky packets due to its own optimization algorithm, udp does not produce sticky packets, and the sent message can be empty, because even if you send an empty message, The protocol will also add a custom header to your empty message, so it is still a datagram, while the tcp protocol cannot send empty messages here. Once an empty message is sent, the receiver will always be in the receiving state, and the sender will send After emptying, it will always be in the state of receiving, so some exception handling code needs to be added to the tcp protocol to prevent the occurrence of exceptions.

  Why is it said that the udp protocol is unreliable and the tcp is reliable? You may be asked in the interview here, and the answer is not as simple as you think (because tcp is based on two-way links and udp is not based on links, so the data can be sent out~~~ If you answer this question, it is estimated that you will be GG in this interview. The real principle:): First of all, a big principle must be figured out. Who does the application deal with when sending and receiving messages? ? ? ——Yes, it is the operating system where the application itself is located. After knowing this, let’s talk about why the tcp protocol is reliable because the server sends data to the client (the data here also flows to the operating system memory of the server first by the service After the terminal operating system sends it to the client), the client must send a confirmation message to the server, and the data sent by the server, the operating system will not immediately clear the data in the memory, but will wait until the confirmation message. Clear the data memory. The data at this time is useless. If the confirmation information is not received, the server will send the data stored in the memory to the client after the interval. This is the reliable nature of tcp protocol communication.

  On the other hand, udp is more casual. After the sender writes the data and clicks to send, the data will be added with a custom header and then sent by the operating system. After sending, the data memory will be cleared immediately. If you want to use udp to effectively transmit data, the maximum data The transmission range should be controlled at 512bytes. If the amount of data exceeds this limit, the stability of data transmission cannot be guaranteed.

2. Complete code logic of tcp protocol

import socket

client = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1',8080))

while True:
    msg=input('>>>: ').strip()
    if not msg:continue
    client.send(msg.encode('utf-8'))
    data=client.recv(1024)
    print(data.decode('utf-8'))

client.close()
client
import socket

server = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1',8080))
server.listen(5)

while True:
    conn,client_addr=server.accept()
    print(client_addr)

    while True:
        try:
            data =conn.recv( 1024 )
             if not data: break # For linux system
            conn.send(data.upper())
        except ConnectionResetError:
            break
    conn.close()

server.close()
Server

3.udp protocol code

Client:

import socket

client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # datagram protocol

while True:
    msg=input('>>>: ').strip()
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
    res,server_addr=client.recvfrom(1024)
    print(res.decode('utf-8'))

Server:

import socket

server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # datagram protocol
server.bind(('127.0.0.1',8080))

while True:
    client_data,client_addr=server.recvfrom(1024)
    msg=input('回复%s:%s>>>:' %(client_addr[0],client_addr[1]))
    server.sendto(msg.encode('utf-8'),client_addr)

4. Implement network communication based on udp writing (recommended version qq)

import socket
server = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('127.0.0.1',8808))

while True:
    data,client_addr=server.recvfrom(1024)
    print('get a message form %s:%s>>:%s'%(client_addr[0],client_addr[1],data.decode('utf-8')))
    msg=input('please recall>>:').strip()
    server.sendto(msg.encode('utf-8'),client_addr)
import socket
client = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)

while True:
    msg=input('what are you want to talk>>:').strip()
    if not msg:continue
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8808))
    msg,addr=client.recvfrom(1024)
    print('get a message from %s:%s>>:%s'%(addr[0],addr[1],msg.decode('utf-8')))

5. Write a time server based on the udp protocol (the access will give you the current time)

Server

import socket,time
server = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('127.0.0.1',8808))

while True:
    data,client_addr=server.recvfrom(1024)
    if not data:
        time_list=time.strftime('%Y-%m-%d %X')
    else:
        time_list=time.strftime(data.decode('utf-8'))
    server.sendto(time_list.encode('utf-8'),client_addr)

access

import socket
client = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)

while True:
    msg=input('please input the format of time which are you want get>>:').strip()
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8808))
    data,addr=client.recvfrom(1024)
    print('time>>:%s'%data.decode('utf-8'))

 

Guess you like

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