实现功能:
客户端发送命令,服务器接收命令并执行
服务端:
import socketserver, os class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): try: while True: self.data=self.request.recv(1024) print("{} send:".format(self.client_address),self.data.decode("utf8")) os.system("%s" % self.data.decode("utf8")) self.request.sendall("脚本开始执行".encode("utf8")) except Exception as e: print(self.client_address,"连接断开") finally: self.request.close() def setup(self): print("before handle,连接建立:",self.client_address) def finish(self): print("finish run after handle") HOST,PORT = "127.0.0.1",9998 server=socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler) #多线程
#server=socketserver.TCPServer((HOST,PORT),MyTCPHandler) #单线程
server.serve_forever()
客户端:
import socket, config client=socket.socket() client.connect(('192.168.175.130',9999))
while True:
cmd=input("(quit退出)>>").strip()
if len(cmd)==0:
continue
if cmd=="quit":
break
client.send(cmd.encode("utf8"))
cmd_res=client.recv(1024)
print(cmd_res.decode("utf8")) client.close()
在编程所遇到的问题
1.编码问题
encode()编码 : str -> bytes
str.encode()
decode()解码 : bytes -> str
bytes.decode()
默认的encoding是 utf-8
参考文档:https://www.cnblogs.com/progor/p/8617042.html#top
修改了通过utf8字符串传输