tcp服务端
from socket import * import subprocess import struct ip_port =('127.0.0.1',8080) back_log = 5 buffer_size = 1024 tcp_server = socket(AF_INET,SOCK_STREAM) tcp_server.bind(ip_port) #地址 tcp_server.listen(back_log) #后面排队的 while True: conn,addr=tcp_server.accept()#等电话 print('新的客户端链接',addr) while True: try: cmd = conn.recv(buffer_size) #收消息 if not cmd:break print('收到客户端的命令',cmd) #执行命令,得到命令的运行结果cmd_res res = subprocess.Popen(cmd.decode('utf8'),shell = True, stderr=subprocess.PIPE, stdin=subprocess.PIPE, stdout=subprocess.PIPE) err = res.stderr.read() if err: cmd_res = err else: cmd_res = res.stdout.read() #发 if not cmd_res: cmd_res = '执行成功'.encode('gbk') length = len(cmd_res) data_length = struct.pack('i',length) conn.send(data_length) #发消息 # client_ready = conn.recv(buffer_size) #制造停顿 # if client_ready == b'ready': conn.send(cmd_res) except Exception as e: print(e) break
tcp客户端
from socket import * import struct from functools import partial ip_port =('127.0.0.1',8080) buffer_size = 1024 tcp_client = socket(AF_INET,SOCK_STREAM) tcp_client.connect(ip_port) while True: cmd = input('==>').strip() if not cmd:continue if cmd == 'quit':break tcp_client.send(cmd.encode('utf8')) #发消息 #解决黏包 length_data = tcp_client.recv(4) # tcp_client.send(b'ready') #制造停顿 length = struct.unpack('i',length_data)[0] recv_size = 0 recv_msg = b'' while recv_size<length: recv_msg += tcp_client.recv(buffer_size) recv_size = len(recv_msg) # recv_msg = ''.join(iter(partial(tcp_client.recv,1024),b'')) print(recv_msg.decode('gbk')) tcp_client.close()