socketserver模块
# 直接实现tcp协议可并发的server端
# server.py
import socketserver
class Myserver(socketserver.BaseRequestHandler): # 必须有这个类 类名随便 但是要继承 socketserver.BaseRequestHandler
def handle(self): # 自动触发了handle方法,并且self.request == conn # 必须有这个handle方法
msg = self.request.recv(1024).decode('utf-8')
self.request.send('1'.encode('utf-8'))
msg = self.request.recv(1024).decode('utf-8')
self.request.send('2'.encode('utf-8'))
msg = self.request.recv(1024).decode('utf-8')
self.request.send('3'.encode('utf-8'))
server = socketserver.ThreadingTCPServer(('127.0.0.1',9000),Myserver) # 固定格式
server.serve_forever() # 服务端为永久工作的,所以是forever
# client
import socket
import time
sk = socket.socket()
sk.connect(('127.0.0.1',9000))
for i in range(3):
sk.send(b'hello,yuan')
msg = sk.recv(1024)
print(msg)
time.sleep(1)
sk.close()
2. 非阻塞IO模型
# server.py
import socket
sk = socket.socket()
sk.bind(('127.0.0.1',9000))
sk.setblocking(False)
sk.listen()
conn_l = []
del_l = []
while True:
try:
conn,addr = sk.accept() # 阻塞,直到有一个客户端来连我
print(conn)
conn_l.append(conn)
except BlockingIOError:
for c in conn_l:
try:
msg = c.recv(1024).decode('utf-8')
if not msg:
del_l.append(c)
continue
print('-->',[msg])
c.send(msg.upper().encode('utf-8'))
except BlockingIOError:pass
for c in del_l:
conn_l.remove(c)
del_l.clear()
sk.close()
# socket的非阻塞io模型 + io多路复用实现的
# 虽然非阻塞,提高了CPU的利用率,但是耗费CPU做了很多无用功
# client
import time
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',9000))
for i in range(30):
sk.send(b'wusir')
msg = sk.recv(1024)
print(msg)
time.sleep(0.2)
sk.close()
3. 验证客户端的合法性
# server.py
import os
import hashlib
import socket
def get_md5(secret_key,randseq):
md5 = hashlib.md5(secret_key)
md5.update(randseq)
res = md5.hexdigest()
return res
def chat(conn):
while True:
msg = conn.recv(1024).decode('utf-8')
print(msg)
conn.send(msg.upper().encode('utf-8'))
sk = socket.socket()
sk.bind(('127.0.0.1',9000))
sk.listen()
secret_key = b'alexsb'
while True:
conn,addr = sk.accept()
randseq = os.urandom(32)
conn.send(randseq)
md5code = get_md5(secret_key,randseq)
ret = conn.recv(32).decode('utf-8')
print(ret)
if ret == md5code:
print('是合法的客户端')
chat(conn)
else:
print('不是合法的客户端')
conn.close()
sk.close()
# client
import hashlib
import socket
import time
def get_md5(secret_key,randseq):
md5 = hashlib.md5(secret_key)
md5.update(randseq)
res = md5.hexdigest()
return res
def chat(sk):
while True:
sk.send(b'hello')
msg = sk.recv(1024).decode('utf-8')
print(msg)
time.sleep(0.5)
sk = socket.socket()
sk.connect(('127.0.0.1',9000))
secret_key = b'alexsb'
randseq = sk.recv(32)
md5code = get_md5(secret_key,randseq)
sk.send(md5code.encode('utf-8'))
chat(sk)
sk.close()