TCP协议
server.py
from socket import socket tcp_server = socket() tcp_server.bind(('127.0.0.1', 9000)) tcp_server.listen() conn, addr = tcp_server.accept() msg = conn.recv(1024) print(msg) conn.send(b'hello from server') conn.close() tcp_server.close()
client.py
from socket import socket tcp_client = socket() tcp_client.connect(('127.0.0.1', 9000)) tcp_client.send(b'hello from client') msg = tcp_client.recv(1024) print(msg) tcp_client.close()
UDP协议
server.py
from socket import socket, SOCK_DGRAM udp_server = socket(type=SOCK_DGRAM) udp_server.bind(('127.0.0.1', 9000)) msg, client_addr = udp_server.recvfrom(1024) print(msg) udp_server.sendto(b'hello from server', client_addr) udp_server.close()
client.py
from socket import socket, SOCK_DGRAM udp_client = socket(type=socket.SOCK_DGRAM) udp_client.sendto(b'hello from client', ('127.0.0.1', 9000)) msg = udp_client.recv(1024) print(msg) udp_client.close()
实现TCP协议可并发的server端
from socketserver import BaseRequestHandler, ThreadingTCPServer class MyServer(BaseRequestHandler): def handle(self): # 自动触发handle方法,self.request 相当于 conn msg = self.request.recv(1024).decode('utf-8') self.request.send('收到'.encode('utf-8')) server = ThreadingTCPServer(('127.0.0.1',9000), MyServer) server.serve_forever()
-
-
报头长度为4个字节,内容是即将发送的报文的字节长度
-
struct模块中的pack方法能够把所有的数字都固定的转换成4字节
-
-
import socket import struct sk = socket.socket() sk.bind(('127.0.0.1', 9000)) sk.listen() conn, _ = sk.accept() byte_len1 = conn.recv(4) size1 = struct.unpack('i', byte_len1)[0] msg1 = conn.recv(size1) print(msg1) byte_len2 = conn.recv(4) size2 = struct.unpack('i', byte_len2)[0] msg2 = conn.recv(size2) print(msg2) conn.close() sk.close()
client.py
import socket import struct sk = socket.socket() sk.connect(('127.0.0.1', 9000)) msg1 = b'hello' byte_len1 = struct.pack('i', len(msg1)) sk.send(byte_len1) sk.send(msg1) msg2 = b'world' byte_len2 = struct.pack('i', len(msg2)) sk.send(byte_len2) sk.send(msg2) sk.close()