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()

 

posted @ 2019-01-11 09:06  梁少华  阅读(334)  评论(0编辑  收藏  举报