Summary of python Network Programming Points

  • 2021-11-13 02:06:11
  • OfStack

Directory Layer 1 and Layer 7 Network Protocols
2. TCP/UDP
3. Example 4, Sticky Package

Layer 1 and Layer 7 network protocols

Should the table will be transmitted to the net to count things:

Application layer, presentation layer, session layer: (These three layers can be merged into application layer, which is the 5-layer network protocol "osi 5-layer protocol") python 'Hello'. encoding ('utf-8')

Transport layer: how to transmit and use ports (port, tcp, udp); Layer 4 routers, Layer 4 switches

Network layer: ip (ipv4 ipv6); Router, Layer 3 Switch

Data link layer: mac (mac, arp protocol: mac can be found through ip); Layer 2 switches, network cards (unicast, broadcast, multicast, arp uses unicast and broadcast)

Physical layer: converted into electrical signals

2. TCP/UDP

tcp needs to establish a connection before it can communicate (similar to making a phone call)

Occupy connection, reliable (message will not be lost), high real-time, slow (inefficient, connection-oriented, reliable, full duplex) Three handshakes The client sends an syn request to the server The server replies to ack and sends an syn request After receiving the request, the client replies to ack and the connection is established In socket, it is done by two commands: client connect () and server accept () Wave 4 times The client sends an fin request to the server The server replies to ack acknowledgement The server sends an fin request to the client Client replies to ack acknowledgement In socket, it is accomplished by two commands: client sk. close () and server conn. close () ack and fin of the server cannot be sent at the same time when waving, because when the client sends all the information, the server does not necessarily send all the information

udp can communicate without establishing a connection (similar to sending messages)

No connection, unreliable (messages may be lost due to network instability), low real-time (efficient, connectionless, unreliable)

3. Examples


'''
------------------------------
TCP Agreement 
------------------------------
'''
'''server'''
import socket

sk = socket.socket()
sk.bind(('127.0.0.1', 6000))
sk.listen()

conn, addr = sk.accept()
conn.send(' How do you do '.encode('utf-8'))
msg = conn.recv(1024)
print(msg.decode('utf-8'))
conn.close()

sk.close()

'''client'''
import socket

sk = socket.socket()
sk.connect(('127.0.0.1', 6000))

msg = sk.recv(1024)
print(msg.decode('utf-8'))
sk.send(' See you later '.encode('utf-8'))

sk.close()

'''
------------------------------
UDP Agreement 
------------------------------
'''
'''server'''
import socket

sk = socket.socket(type=socket.SOCK_DGRAM)   #SOCK_DGRAM udp    default tcp
sk.bind(('127.0.0.1', 6000))

# msg = sk.recv(1024)
# print(msg.decode('utf-8'))

while True:
    msg = sk.recvfrom(1024)
    print(msg)
    print(msg[0].decode('utf-8'))
    if msg[0].decode('utf-8') == ' The other party is disconnected from you ':
        continue
    msgSend = input('>>>')
    sk.sendto(msgSend.encode('utf-8'), msg[1])

'''client'''
import socket

sk = socket.socket(type=socket.SOCK_DGRAM)
server = ('127.0.0.1', 6000)

while True:
    msgSend = input('>>>')
    if msgSend.upper() == 'Q':
        sk.sendto(' The other party is disconnected from you '.encode('utf-8'), server)
        break
    sk.sendto(msgSend.encode('utf-8'), server)
    msg = sk.recv(1024).decode('utf-8')
    if msg.upper() == 'Q':
        print(' The other party is disconnected from you ')
        break
    print(msg)

4. Stick the bag

It only appears in tcp protocol, because there is no boundary between multiple messages in tcp protocol, and there are various optimization algorithms, which will lead to packet sticking at both the sender and the receiver:

Sender: Two messages are very short, and the interval between sending is also very short

Receiver: Multiple messages are not received in time, and the cache heap at the receiver is 1, resulting in sticky packets


'''server'''
import socket

sk = socket.socket()
sk.bind(('127.0.0.1', 6000))
sk.listen()

conn, addr = sk.accept()
conn.send(b'hello')
conn.send(b'byebye')

conn.close()
sk.close()

'''client'''
import time
import socket

sk = socket.socket()
sk.connect(('127.0.0.1', 6000))

time.sleep(0.1)
msg = sk.recv(5)
print(msg)
msg = sk.recv(4)
print(msg)

sk.close()

The essence of solving the sticky packet problem: set the boundary (send length, send message, alternate)

1. Custom protocol


'''server'''
import socket

sk = socket.socket()
sk.bind(('127.0.0.1', 6000))
sk.listen()

conn, addr = sk.accept()
msg1 = input('>>>').encode('utf-8')
msg2 = input('>>>').encode('utf-8')

def sendFunc(msg):
    num = str(len(msg))
    ret = num.zfill(4)
    conn.send(ret.encode('utf-8'))
    conn.send(msg)
sendFunc(msg1)
sendFunc(msg2)

conn.close()
sk.close()

'''client'''
import socket

sk = socket.socket()
sk.connect(('127.0.0.1', 6000))

def receiveFunc():
    num = sk.recv(4).decode('utf-8')
    msg = sk.recv(int(num))
    print(msg.decode('utf-8'))

receiveFunc()
receiveFunc()

sk.close()

2. struct module


import struct
'''~2**32,  Excluding sign bits, equivalent to 1G The length of the data of '''

num1 = 1231341234
num2 = 1342342
num3 = 12

ret1 = struct.pack('i', num1)
print(ret1)
print(len(ret1))
ret2 = struct.pack('i', num2)
print(ret2)
print(len(ret2))
ret3 = struct.pack('i', num3)
print(ret3)
print(len(ret3))

ret11 = struct.unpack('i', ret1)
print(ret11)
print(type(ret11[0]))

The above is the python network programming points summary of the details, more information about python network programming please pay attention to other related articles on this site!


Related articles: