server端:
1. 阻塞型套接字,不能满足多个客户端同时访问
import socket
server = socket.socket()
server.bind((""127.0.0.1,8898))
while True:
server.listen(2) 2为最大同时连接数,python3.6以上有用
conn,addr = server.accept()
data = conn.recv(1024) 1024为最大接收字节
conn.close() 服务器连接关闭
图例:
2. 非阻塞形套接字,用单线程模拟多线程并发,实现多个客户端同时访问
import socket
server = socket.socket()
server.setblocking(False)
server.bind(("127.0.0.1",8898))
server.listen(5)
conn_list = [] 储存客户端请求
while True:
try:
conn,addr = server.accept()
conn.setblocking(False)
conn_list.append(conn)
except BlockingIOError:
pass
for conn in conn_list:
try:
data = conn.recv(1024)
if data:
print(data)
conn.send(data)
else:
conn.close()
conn_list.remove(conn)
except BlockingIOError:
pass
图例:
client端:
import socket
client = socket.socket()
client.connect(("127.0.0.1",8898))
client.send(b"hello")
client.close()
图例: