socketserver.py
import socket
server = socket.socket() # 获得socket实例
server.bind(("localhost", 9998)) # 绑定ip port
server.listen() # 开始监听
print("等待客户端的连接...")
conn, addr = server.accept() # 接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
print("新连接:", addr)
while True:
data = conn.recv(1024)
if not data:
print("客户端断开了...")
break
print("收到消息:", data)
conn.send(data.upper())
server.close()
socketclient.py
import socket
client = socket.socket()
client.connect(("localhost", 9998))
while True:
msg = input(">>:").strip()
if msg == "quit()":
client.close()
if len(msg) == 0:
continue
client.send(msg.encode("utf-8"))
data = client.recv(1024)
print("来自服务器:", data)
client.close()
sock_server_ssh.py
__author__ = "Alex Li"
import socket, os, time
server = socket.socket()
server.bind(('localhost', 6666))
server.listen()
while True:
conn, addr = server.accept()
print("new conn:", addr)
while True:
print("等待新指令")
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")) # 先发大小给客户端
time.sleep(0.5)
conn.send(cmd_res.encode("utf-8")) # 再发内容给客户端
print("send done")
# os.path.isfile()
# os.stat("sock")
server.close()
sock_server_client.py
__author__ = "Alex Li"
import socket
client = socket.socket()
#client.connect(('192.168.16.200',9999))
client.connect(('localhost', 6666))
while True:
cmd = input(">>:").strip()
if len(cmd) == 0:
continue
client.send(cmd.encode("utf-8")) # 客户端输入转化为bytes
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判断
#print(data.decode())
received_data += data
# 数据完成接收,达到长度
else:
print("cmd res receive done...", received_size)
print(received_data.decode())
client.close()