客户端代码:
1 import socket
2 sk = socket.socket()
3 address = ('127.0.0.1',8006)
4 sk.connect(address)
5 print('已连接')
6
7 while True:
8 inp = input('>>>')
9 if inp == 'exit':
10 break
11 elif inp == '':
12 print('不能输入空白字符')
13 continue
14 sk.send(bytes(inp,'utf8'))
15 result_len = int(str(sk.recv(1024),'utf8')) #接收结果的长度
16 print(result_len)
17 data = bytes()
18 while len(data) != result_len:
19 receive = sk.recv(1024)
20 data += receive
21 print(str(data,'gbk'))
1.当结果较大时,一次接收不完,需要循环接收
2.通过比较已接收内容的大小与完整结果的大小判断是否接收完毕
3.19行:我们收到的内容是Windows帮我们将读到的内容编码为bytes类型,而Windows默认是gbk
所以在21行,解码时要用gbk
服务端代码:
1 import subprocess #该模块用来执行cmd命令
2 import socket
3 sk = socket.socket()
4 address = ('127.0.0.1',8006)
5 sk.bind(address)
6 sk.listen(3)
7
8 while True:
9 print('waiting for connection..........')
10 conn,addr = sk.accept()
11 while True:
12 try:
13 data = str(conn.recv(1024),'utf8')
14 if data != '':
15 print(data)
16 else:
17 continue
18 except Exception as e:
19 print(e)
20 break
21 obj = subprocess.Popen(data,shell=True,stdout=subprocess.PIPE)
22 cmd_result = obj.stdout.read() #读取cmd命令的结果,该结果就是bytes类型
23 result_len = str(len(cmd_result)) #计算结果的大小
24 conn.send(bytes(result_len,'utf8')) #先发送一个结果的大小
25 conn.sendall(cmd_result) #发送命令执行的内容
26 sk.close()
bytes类型与整型不能互转,必须用bytes与str的互转做过渡