zoukankan      html  css  js  c++  java
  • socketserver模块(实现并发)

    socketserver模块(实现并发)

    一、基于UDP协议实现的并发

    # 服务端
    import socketserver
    
    class MyServer(socketserver.BaseRequestHandler):
        def handle(self):
            # print('来啦 老弟')
            while True:
                data,sock = self.request
                print(self.client_address)  # 客户端地址
                print(data.decode('utf-8'))
                sock.sendto(data.upper(),self.client_address)
    
    
    if __name__ == '__main__':
        """只要有客户端连接  会自动交给自定义类中的handle方法去处理"""
        server = socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyServer)  # 创建一个基于UDP的对象
        server.serve_forever()  # 启动该服务对象
    
    # 客户端
    import socket
    import time
    
    client = socket.socket(type=socket.SOCK_DGRAM)
    server_address = ('127.0.0.1',8080)
    
    while True:
        client.sendto(b'hello',server_address)
        data,addr = client.recvfrom(1024)
        print(data.decode('utf-8'),addr)
        time.sleep(1) # 发送间隔太短的话,看不出效果
    

    二、基于TCP协议实现的并发

    # 服务端
    import socketserver
    
    class MyServer(socketserver.BaseRequestHandler):
        def handle(self):
            # print('来啦 老弟')
            while True:
                data = self.request.recv(1024)
                print(self.client_address)  # 客户端地址
                print(data.decode('utf-8'))
                self.request.send(data.upper())
    
    
    if __name__ == '__main__':
        """只要有客户端连接  会自动交给自定义类中的handle方法去处理"""
        server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer)  # 创建一个基于TCP的对象
        server.serve_forever()  # 启动该服务对象
        
    # 客户端
    import socket
    
    client = socket.socket()
    client.connect(('127.0.0.1',8080))
    
    while True:
        client.send(b'hello')
        data = client.recv(1024)
        print(data.decode('utf-8'))
    
  • 相关阅读:
    ChromeDriver下载
    LR基础理论详解
    python中assert详解
    python定义类()中写object和不写的区别
    python list初始化技巧
    python list中append()方法和extend()方法区别
    python生成器(generator)、迭代器(iterator)、可迭代对象(iterable)区别
    使用__slots__节省python内存技巧
    lambda表达式详解
    python处理数据问题详解
  • 原文地址:https://www.cnblogs.com/DcentMan/p/11380543.html
Copyright © 2011-2022 走看看