python asyncore异步通信

空扰寡人 提交于 2019-12-09 21:40:04
import asyncore
import socket

class Server(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        print('Binding to', self.socket.getsockname())
        self.listen(5)

    def handle_accept(self):
        sock, address = self.accept()
        print('Got a new client', address)
        self.sim_handler = Handler(sock=sock)

class Handler(asyncore.dispatcher):
    def handle_write(self):
        self.send('hi'.encode())

    def handle_read(self):
        print(self.recv(1024).decode('utf-8'))

class Client(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))

    def handle_write(self):
        self.send('hello'.encode())

    def handle_read(self):
        print(self.recv(1024).decode('utf-8'))
        
server = Server('localhost', 9090)
client = Client('localhost', 9090)
asyncore.loop(count=10)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!