Socket实现套接字通信
套接字工作流程:
一、简单socket通信
①服务端
import socket # 1 买手机 phone = socket.socket() # 2 绑定手机卡 phone.bind(('127.0.0.1', 8080)) # 3 开机 phone.listen(5) # 4 等电话连接 conn, addr = phone.accept() # 5 收发消息 data = conn.recv(1024) # 1、单位:bytes 2:1024代表最大接收1024个bytes print('客户端的数据', data) conn.send(data.upper()) # 6 挂电话 conn.close() # 7 关机 phone.close()
②客户端
import socket # 1 买手机 phone = socket.socket() # 2 拨号 phone.connect(('127.0.0.1', 8080)) # 3 发收数据 phone.send('hello'.encode('utf-8')) data = phone.recv(1024) print(data) # 4 关机 phone.close()
先运行服务端代码、再运行客户端代码,打印的结果:
服务端:
客户端:
二、通信循环
①服务端
import socket phone = socket.socket() phone.bind(('127.0.0.1', 8080)) phone.listen(5) conn, addr = phone.accept() # 通信循环 while True: try: data = conn.recv(1024) # 1、单位:bytes 2:1024代表最大接收1024个bytes # 针对于Linux系统 if not data: break print('客户端的数据', data) conn.send(data.upper()) except ConnectionResetError: break conn.close() phone.close()
②客户端
import socket phone = socket.socket() phone.connect(('127.0.0.1', 8080)) while True: msg = input('>>>:').strip() if not msg: continue phone.send(msg.encode('utf-8')) data = phone.recv(1024) print(data.decode('utf-8')) phone.close()
先运行服务端代码、再运行客户端代码,打印的结果:
服务端:
客户端:
三、链接循环
①服务端
import socket phone = socket.socket() phone.bind(('127.0.0.1', 8080)) phone.listen(5) # 链接循环 while True: conn, addr = phone.accept() # 通信循环 while True: try: data = conn.recv(1024) # 1、单位:bytes 2:1024代表最大接收1024个bytes # 适用于Linux系统 if not data: break print('客户端的数据', data) conn.send(data.upper()) except ConnectionResetError: break conn.close() phone.close()
②客户端
import socket phone = socket.socket() phone.connect(('127.0.0.1', 8080)) while True: msg = input('>>>:').strip() if not msg: continue phone.send(msg.encode('utf-8')) data = phone.recv(1024) print(data.decode('utf-8')) phone.close()
四、模拟ssh远程执行命令
服务端:
客户端: