1.基于tcp协议实现简单套接字通信
# server.py
import socket
# 1、买手机
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SOCK_STREAM=》TCP协议
# 2、插手机卡
phone.bind(("127.0.0.1", 8080)) # 本地回环
# 3、开机
phone.listen(5)
print('starting %s:%s' %("127.0.0.1", 8080))
# 4、等电话链接
conn, client_addr = phone.accept()
# 5、收/发消息
data = conn.recv(1024) # 最大接收的字节个数
print("收到的客户端数据:", data.decode('utf-8'))
conn.send(data.upper())
# 6、关闭
conn.close() # 挂电话
phone.close() # 关机
# client.py
import socket
# 1、买手机
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SOCK_STREAM=》TCP协议
# 2、拨电话
phone.connect(("127.0.0.1", 8080))
# 3、发/收消息
phone.send("hello".encode('utf-8'))
data = phone.recv(1024)
print("服务的返回的数据:", data.decode('utf-8'))
# 4、关闭
phone.close()
2.加上循环的套接字通信
# server.py
"""
服务端应该满足的特性:
1、一直对外提供服务
2、并发地提供服务
"""
import socket
# 1、买手机
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SOCK_STREAM=》TCP协议
# 2、插手机卡
phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #就是它,在bind前加
phone.bind(("127.0.0.1", 8080)) # 本地回环
# 3、开机
phone.listen(5)
print('starting %s:%s' %("127.0.0.1", 8080))
# 4、等电话链接=>链接循环
while True:
conn, client_addr = phone.accept()
print(client_addr)
# 5、收/发消息=>通信循环
while True:
try:
data = conn.recv(1024) # 最大接收的字节个数
if len(data) == 0: # 针对linux系统
break
print("收到的客户端数据:", data.decode('utf-8'))
conn.send(data.upper())
except Exception: # 针对windows系统
break
# 6、关闭
conn.close() # 挂电话
phone.close() # 关机
# client.py
import socket
# 1、买手机
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SOCK_STREAM=》TCP协议
# 2、拨电话
phone.connect(("127.0.0.1", 8080))
# 3、发/收消息=>通信循环
while True:
msg = input(">>: ").strip()
phone.send(msg.encode('utf-8'))
data = phone.recv(1024)
print("服务的返回的数据:", data.decode('utf-8'))
# 4、关闭
phone.close()
3.远程执行命令
# server.py
"""
服务端应该满足的特性:
1、一直对外提供服务
2、并发地提供服务
"""
import socket
import subprocess
# 1、买手机
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SOCK_STREAM=》TCP协议
# 2、插手机卡
phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 就是它,在bind前加
phone.bind(("127.0.0.1", 8080)) # 本地回环
# 3、开机
phone.listen(5)
print('starting %s:%s' % ("127.0.0.1", 8080))
# 4、等电话链接=>链接循环
while True:
conn, client_addr = phone.accept()
print(client_addr)
# 5、收/发消息=>通信循环
while True:
try:
cmd = conn.recv(1024) # 最大接收的字节个数
if len(cmd) == 0: # 针对linux系统
break
obj = subprocess.Popen(cmd.decode('utf-8'),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
res=obj.stdout.read()+obj.stderr.read() # ???
print(res)
conn.send(res)
except Exception: # 针对windows系统
break
# 6、关闭
conn.close() # 挂电话
phone.close() # 关机
# client.py
import socket
# 1、买手机
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SOCK_STREAM=》TCP协议
# 2、拨电话
phone.connect(("127.0.0.1", 8080))
# 3、发/收消息=>通信循环
while True:
cmd = input("[root@localhost]# ").strip()
phone.send(cmd.encode('utf-8'))
data = phone.recv(1024)
print(data.decode('gbk'))
# 4、关闭
phone.close()