初学socket 觉得很有趣,下面是刚刚学习的代码,提供出来,给大家一起学习一下
首先展示的是服务器端的代码:
import socket
import os
server = socket.socket()
server.bind(('localhost',6960))
print("我要开始等电话了")
server.listen()
while True:
conn,addr = server.accept()
print(conn,addr)
print("电话来了")
while True:
print("等待新的指令")
data = conn.recv(1024)
if not data:
print("客服端已断开")
break
print("recv:",data)
cmd_res = os.popen(data.decode()).read()
print("brfore send",len(cmd_res))
if len(cmd_res) == 0:
cmd_res = "cmd has no output"
conn.send(str(len(cmd_res)).encode("utf-8")) #先发大小给客服端
conn.send(cmd_res.encode("utf-8"))
print("send done")
server.close()
接下来是客服端的代码:
import socket
import os
client = socket.socket()
client.connect(('localhost',6960))
while True:
msg = input(">>>:").strip()
if len(msg) == 0:continue
client.send(msg.encode("utf-8")) #
data_size = client.recv(1024) #介绍命令结果的大小
print("命令结果大小:",data_size)
received_size = 0
received_data = b''
while received_size < int(data_size.decode()):
data = client.recv(1024)
received_size += len(data) #每次手打的有肯能小于1024,所以必须用len判断
#print(data.decode())
received_data += data
else:
print("cmd_res receive done",received_size)
print(received_data.decode())
#data = client.recv(1024)
#print("recv",data.decode())
client.close()