zoukankan      html  css  js  c++  java
  • 客户端验证、tcp协议中多个客户端的同时在线

    一、客户端验证

      当在一个局域网内需要验证是否为合法的客户端连接时,我们需要写代码进行验证。

      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 True
        else:
            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.request
            while 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()
  • 相关阅读:
    pytest.4.Fixture
    pytest.3.Assert
    pytest.2.运行多个文件
    [LeetCode 378.] Kth Smallest Element in a Sorted Matrix
    priority_queue 自定义 comparator
    原地调整法查找数组元素
    [LeetCode 436.] Find Right Interval
    [LeetCode 611.] Valid Triangle Number
    二叉树Morris遍历
    用户态IO:DPDK
  • 原文地址:https://www.cnblogs.com/youhongliang/p/9664433.html
Copyright © 2011-2022 走看看