#server
import socket,os
server = socket.socket()
server.bind(('localhost',9999))
server.listen()
while true:
conn,addr=server.accept()
while true:
data = conn.recv(1024)
if not data:
print("客戶端已經斷開")
break
print("執行指令",data)
cmd_res = os.popen(data.decode()).read()#接受字串,執行結果是字串
print("before send",len(cmd_res))
if len(cmd_res) == 0:
cmd_res = "cmd has no output..."
conn.send( str (len(cmd_res.encode())).encode("utf-8"))#先發大小給客戶端
conn.send(cmd_res.encode("utf-8"))
print("semd done")
server.close()
#client
import socket
client = socket.socket()
client.connect(("localhost",9999))
while true:
cmd = input(">>:").strip()
if len(cmd) ==0 :continue
client.send(cmd.encode('utf-8'))
cmd_res_size = client.recv(1024)#接受命令的長度
print("命令結果大小:",cmd_res_size)
received_size= 0
received_data=b''
while received_size< int(cmd_res_size.decode()):
data = client.recv(1024)
received_size +=len(data)#每次收到的有可能小於1024,所以必須用len判斷
received_data +=data
else:
print("cmd res receive done...",received_size)
print(received_data.decode())
client.close()
python socket 簡單程式設計
伺服器端 import socket s socket.socket host socket.gethostname port 1234 s.bind host,port s.listen 5 while true c,addr s.accept print got connection from ...
python socket簡單使用 一
匯入socket模組 import socket socket可以看做為乙個檔案,用乙個socket表示 開啟了乙個網路鏈結 開啟乙個socket需要知道目標計算機的ip位址和埠號 建立tcp連線是,自動發起連線的叫做客戶端,被動響應連線的叫做伺服器 新建乙個socket物件 原型 socket.s...
簡單的python socket程式設計
最近寫點小東西,要用到socket伺服器和客戶端,用python實現起來非常的方便。貼點 首先 引用必要的包 import thread from socket import from time import ctime接下來定義埠號和位址 host port 8888 埠號 bufsize 200...