程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

9、 Python learning notes - network programming - socketserver exercise

編輯:Python

socketserver Version remote execution command client End .

import socket
sk = socket.socket()
address = ("127.0.0.1", 8088)
sk.connect(address)
while True:
cmd = input(" Please enter a command :")
sk.sendall(bytes(cmd, encoding='utf8'))
if cmd == 'exit':
break
len_result = sk.recv(1024)
len_result = int(str(len_result, encoding='utf8'))
sk.sendall(bytes("ok", encoding='utf8'))
result = bytes()
while len(result) != len_result:
date = sk.recv(1024)
result += date
print(str(result, encoding='gbk'))
sk.close()

socketserver Version remote execution command server End

import socketserver
import subprocess
class Myserver(socketserver.BaseRequestHandler):
def handle(self):
print(" Server side start ")
conn = self.request
print(conn)
client_address = self.client_address
while True:
try:
cmd = str(conn.recv(1024), encoding='utf8')
except Exception as e:
print(e)
break
if cmd == 'exit':
break
print(" client :{}, command :{}".format(client_address, cmd))
cmd_result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
cmd_result_stdout = cmd_result.stdout.read()
cmd_result_stderr = cmd_result.stderr.read()
if len(cmd_result_stdout) == 0:
result = cmd_result_stderr
else:
result = cmd_result_stdout
conn.sendall(bytes(str(len(result)), encoding='utf8'))
conn.recv(1024)
conn.sendall(result)
conn.close()
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1', 8088), Myserver)
server.serve_forever()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved