UDP协议套接字编程
不用连接直接进行传输
服务端
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('127.0.0.1', 8000))
print('wait...')
while True:
data, client_addr = server.recvfrom(1024)
print(data, client_addr)
server.sendto(data.upper(), client_addr)
客户端
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
msg = input('please your enter msg')
client.sendto(msg.encode('utf-8'), ('127.0.0.1', 8000))
data, server_addr = client.recvfrom(1024)
print(data, server_addr)
socketserver实现高并发
实现同一时刻有多个人接听
服务端
import socketserver
import subprocess
import struct
# 继承父类的连接循环
class MyHandler(socketserver.BaseRequestHandler):
# 自己写一个通信循环,不用父类的
def handle(self):
while True:
try:
cmd = self.request.recv(1024)
print(cmd)
pipeline = subprocess.Popen(cmd.decode('utf8'),
shell=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
stdout = pipeline.stdout.read()
stderr = pipeline.stderr.read()
count_len = len(stdout) + len(stderr)
guding_bytes = struct.pack('i', count_len)
self.request.send(guding_bytes) # 4
self.request.send(stderr + stdout)
except ConnectionResetError:
break
# 使用socketserver的连接循环(并发),但是使用了自己的通信循环
# myhandler = MyHandler()
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1', 8000), MyHandler, bind_and_activate=True)
print('start...')
server.serve_forever()
客户端(可以使用多个)
import socket
import struct
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8080))
while True:
msg = input('please your enter msg')
phone.send(msg.encode('utf-8'))
count_len = phone.recv(4)
res_len = struct.unpack('i', count_len)[0]
data = phone.recv(res_len)
print(data.decode('gbk'))