zoukankan      html  css  js  c++  java
  • socketserver的使用

    socketserver底层也是使用线程实现的并发,直接上代码

    # server
    
    import socketserver
    
    '''
    socketserver使用模式:
    
    1 功能类
    
    class Myserver(socketserver.BaseRequestHandler)  #
        def handle(self):
            pass
    
    
    2  server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),Myserver)
    
    
    
    3  server.serve.forever()
    '''
    
    class Myserver(socketserver.BaseRequestHandler):  #
        def handle(self):
            '''
            并发的业务逻辑
            :return:
            '''
            while 1:
                client_data = self.request.recv(1024)
                print(client_data.decode('utf-8'))
                if client_data.decode('utf-8') == 'exit':
                    print('客户端断开链接,等待新的用户连接......')
                    break
                print('接收数据>>>', str(client_data, 'utf-8'))
                response = input('响应数据 >>>')
                self.request.sendall(bytes(response, 'utf-8'))
    
            self.request.close()
    
    # 1. self.socket   2 self.socket.bind()   3.  self.socket.listen(5)
    server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),Myserver)
    
    server.serve_forever()
    
    
    
    
    # client
    from socket import *
    
    client = socket(AF_INET, SOCK_STREAM)
    client.connect(('127.0.0.1', 8080))
    
    while True:
        res = input('>>>').strip()
        if not res: continue
        client.send(res.encode('utf-8'))
        data = client.recv(1024)
        print(data.decode('utf-8'))
    
    client.close()

  • 相关阅读:
    Java程序员必知的8大排序
    JQUERY 展开收起显示隐藏效果
    Java程序员必知的8大排序
    辞职申请
    值得收藏的Microsoft SQL Server下的SQL语句
    SQL
    sql language
    insert with special ID
    ExcuteNonQuery
    JS
  • 原文地址:https://www.cnblogs.com/lshedward/p/10253487.html
Copyright © 2011-2022 走看看