1. 程式人生 > >Python隨心記--socket-tcp

Python隨心記--socket-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('utf-8'),shell=True, stderr=subprocess.PIPE, stdout
=subprocess.PIPE, stdin=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) conn.send(cmd_res) except Exception as e: print(e) break #客戶端 from socket import * import struct from functools import partial ip_port=('127.0.0.1',8080) back_log=5 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('utf-8')) #解決粘包 length_data=tcp_client.recv(4) length=struct.unpack('i',length_data)[0] recv_size=0 recv_data=b'' while recv_size < length: recv_data+=tcp_client.recv(buffer_size) recv_size=len(recv_data) print('命令的執行結果是 ',recv_data.decode('gbk')) tcp_client.close()