Python编程—SOCKET开发
最近学习Python编程—socket模块,编写一个基于C/S(Client/Server)架构的简单的聊天工具软件。
Socket介绍
Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。socket起源于Unix/Linux基本哲学之一就是“一切皆文件”,Socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO, 打开、关闭)。
开发环境
操作系统:macOS Monterey 12.5.1
IDE: PyCharm2020.1
运行环境
操作系统:Win10 , macOS
服务器端软件源码
import socket
HOST = ''
PORT = 50007
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) # 防止地址占用错误发生(Address already in use)
socket_server.bind((HOST, PORT))
while 1:
conn, addr = socket_server.accept()
with conn:
print('Connected by', addr)
while 1:
data = conn.recv(1024)
print('Recv from ', conn.getpeername(), data.decode())
if not data:
print('对方已下线!')
break
response = input('>>>: ').strip()
conn.send(response.encode())
print('send to ', conn.getpeername(), response)
客户端软件源码
import socket
HOST = '192.168.31.246' # remote host IP
PORT = 50007
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
while 1:
msg = input('>>>: ')
if len(msg) == 0:continue
if msg == 'quit':break
client.sendall(msg.encode())
data = client.recv(1024)
print('Received from ', data.decode())
运行结果如下图:
< 服务器端 >
<客户端>