今日作业:通过开启子进程的方式实现套接字服务端可以并发的处理多个链接以及通讯循环(用到了subprocess模块,解决粘包问题)
server(服务端)
import socket
from multiprocessing import Process
import subprocess, struct
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #
server.bind(('127.0.0.1',8080))
server.listen(5)
def talk(conn,client_addr):
print(client_addr)
while True:
data = conn.recv(1024)
if len(data) == 0:
break
print(data)
obj = subprocess.Popen(str(data, \
encoding='utf-8'), shell=True, \
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
msg = obj.stdout.read()
import json
dic = {'size': len(msg)}
dic_bytes = (json.dumps(dic)).encode('utf-8')
head_count = struct.pack('i', len(dic_bytes))
print(dic)
conn.send(head_count)
conn.send(dic_bytes)
conn.send(msg)
if __name__ == '__main__': # windows下start进程一定要写到这下面
while True:
conn,client_addr=server.accept()
p=Process(target=talk,args=(conn,client_addr))
p.start()
client(客户端)
import socket
import struct
import json
soc=socket.socket()
soc.connect(('127.0.0.1',8080))
while True:
in_s=input('请输入要执行的命令:')
soc.send(in_s.encode('utf-8'))
head_dic_len=soc.recv(4)
head_l=struct.unpack('i',head_dic_len)[0]
dic_byte=soc.recv(head_l)
head=json.loads(dic_byte)
print(head)
l=head['size']
count=0
data_total=b''
print(l)
while count<l:
if l<1024: #如果接受的数据小于1024 ,直接接受数据大小
data=soc.recv(l)
else:#如果接受的数据大于1024
if l-count>=1024: #总数据长度-count(目前收到多少,count就是多少) 如果还大于1024 ,在收1024
data=soc.recv(1024)
else: #总数据长度-count(目前收到多少,count就是多少) 如果小于1024,只收剩下的部分就可
data=soc.recv(l-count)
data_total+=data
count+=len(data)
print(data_total.decode('gbk'))