一、客户端验证
当在一个局域网内需要验证是否为合法的客户端连接时,我们需要写代码进行验证。
Server端
import os
import hmac
import socket
def auth(conn):msg = os.urandom(32)conn.send(msg)result = hmac.new(secret_key, msg)client_digest = conn.recv(1024)if result.hexdigest() == client_digest.decode('utf-8'):print('是合法的链接')return Trueelse:print('不合法的链接')return False
secret_key = b'alex_sb'
sk = socket.socket()
sk.bind(('127.0.0.1',9000))
sk.listen()
conn,addr = sk.accept()if auth(conn):print(conn.recv(1024))# 正常的和client端进行沟通了
conn.close()
else:conn.close()
sk.close()
Client端
import hmac
import socket
def auth(sk):msg = sk.recv(32)result = hmac.new(secret_key,msg)res = result.hexdigest()sk.send(res.encode('utf-8'))secret_key = b'alex_sb'
sk = socket.socket()
sk.connect(('127.0.0.1',9000))
auth(sk)
sk.send(b'upload')
# 进行其他正常的和server端的沟通
sk.close()
二、Tcp协议中多个客户端同时在线的功能的实现:
Server端
import socketserver # tcp协议端的server端就不需要导入socket
class Myserver(socketserver.BaseRequestHandler):def handle(self):conn = self.requestwhile True:conn.send(b'hello')print(conn.recv(1024))
server = socketserver.ThreadingTCPServer(('127.0.0.1',9000),Myserver)
server.serve_forever()
Client端
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',9000))
while True:sk.send(b'hello')msg = sk.recv(1024)print(msg)
sk.close()