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)
来源:CSDN
作者:飞翔的貅貅
链接:https://blog.csdn.net/ytreel/article/details/103464161