python foundation network programming part02

Keywords: Python socket

TCP protocol

TCP is a transmission control protocol, which establishes a two-way channel.

Three handshakes to establish a connection

  • The client sends a connection request to the server
  • The server receives the request and returns the confirmation information to the client, and sends the connection request to the client
  • The client receives the request and returns the confirmation information to the server

Feedback mechanism: a request must have a response. After receiving the request, the other party must be informed that the request has been received.

Four waves, disconnected

  • Client sends disconnected request to server
  • The server receives the request return confirmation information and sends it to the client
  • After the server confirms that all data has been received, it sends the disconnected request to the client
  • The client receives the request and returns the confirmation information to the server

Socket socket communication

Definition: python's built-in module, also known as socket, is used to encapsulate the Internet Protocol (the layer below the application layer)

Function: realize the work below the application layer of internet protocol and improve the development efficiency

Usage: see code

  • server.py
import socket

# Get socket object
server = socket.socket()
# Binding server ip address and port
# 127.0.0.1 is the loopback address, indicating the local ip address
server.bind(('127.0.0.1', 8080))
# Semi data pool, indicating how many clients can access it at the same time.
# listen(n):n+1 clients
server.listen(5)
# Block until client access, return connection request and client IP
conn, client = server.accept()
# Receive information sent by client and print
# Default maximum number of bytes received: 1024 (adjustable according to memory)
client_data = conn.recv(1024).decode('utf-8')
print(f"Message from client:{client_data}")
# Send message to client
send_msg = input("Please input the instruction>>>>>: ").strip().encode('utf-8')
conn.send(send_msg)

# Close connection
conn.close()
# Shut down service
server.close()
  • client.py
import socket

# Create socket object
client = socket.socket()
# Request connection from server
client.connect(('127.0.0.1', 9527))
# Send data to the server, send only receives binary data
client_msg = input("Please input the information to be sent to the server>>>>:").strip()
client.send(client_msg.encode('utf-8'))
# Receive data returned by the server
# Default maximum number of bytes received: 1024 (adjustable according to memory)
client_data = client.recv(1024).decode('utf-8')
print(f"Messages from the server:{client_data}")
# Close connection
client.close()

Be careful:

  • Start the server first, then the client
  • A data request must have a response. The server and the client cannot send or receive the request at the same time

Sticking phenomenon

  • Phenomenon 1: when the time interval of sending data multiple times is short and the amount is small, the information is read by the transfer once, and the subsequent reading record is empty
# Client.py
import socket

server = socket.socket()
server.connect(("127.0.0.1", 9527))

# Continuous transmission
server.send(b"hello")
server.send(b"hello")
server.send(b"hello")

server.close()
# Server.py
import socket
from socket import SOL_SOCKET
from socket import SO_REUSEADDR

server = socket.socket()
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 9527))
server.listen(5)
conn, client = server.accept()

data1 = conn.recv(1024)
data2 = conn.recv(1024)
data3 = conn.recv(1024)

print(data1)
print(data2)
print(data3)

conn.close()
server.close()

Output result

b'hellohellohello'
b''
b''
  • Phenomenon 2: when the number of bytes of data sent exceeds the maximum number of bytes received each time, records that were not received last time will be received next time
# Client.py
import socket

client = socket.socket()
client.connect(('127.0.0.1', 9527))
client.send(b'hello world!')
client.send(b'lift is smart!')
client.close()
# Server.py
import socket
from socket import SOL_SOCKET
from socket import SO_REUSEADDR

server = socket.socket()
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind(('127.0.0.1', 9527))
server.listen(5)

conn, client = server.accept()

re_data1 = conn.recv(5).decode('utf-8')
re_data2 = conn.recv(5).decode('utf-8')

print(re_data1)
print(re_data2)
conn.close()
server.close()

Output result

hello
 worl

struct module solving the problem of sticking package

Definition: python's built-in module can package fixed length data into fixed format length

Function: make the real data into a fixed length header, the client sends it to the server, and the server can receive the header (and vice versa). Then unpack the header to get the length of the real data and receive it.

Use, take phenomenon 2 as an example (solve in essence)

# Client.py
import socket
import struct

client = socket.socket()
client.connect(('127.0.0.1', 9527))
msg1 = 'hello world!'
# Using the pack method in struct module, pattern 'i' represents 4 bytes
# Package the length of data to be sent into a header
header1 = struct.pack('i', len(msg1))
# Send the hair to the server first
client.send(header1)
# Then send the real data to the server
client.send(msg1.encode('utf-8'))
# Server.py
import socket
import struct

server = socket.socket()
server.bind(('127.0.0.1', 9527))
server.listen(5)
conn, client = server.accept()

# Read header
header = conn.recv(4)
# Using struct.unpack to parse the real data length
header_len = struct.unpack('i', header)[0]

# Read real data
re_data = conn.recv(header_len)

print(re_data.decode('utf-8'))
conn.close()
server.close()

Posted by WolfRage on Thu, 05 Dec 2019 16:15:43 -0800