我正在阅读有关如何使用模块asynchat的帖子(http://pymotw.com/2/asynchat/#module-asynchat)。这是服务器的代码
import asyncore
import logging
import socket
from asynchat_echo_handler import EchoHandler
class EchoServer(asyncore.dispatcher):
"""Receives connections and establishes handlers for each client.
"""
def __init__(self, address):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(address)
self.address = self.socket.getsockname()
self.listen(1)
return
def handle_accept(self):
# Called when a client connects to our socket
client_info = self.accept()
EchoHandler(sock=client_info[0])
# We only want to deal with one client at a time,
# so close as soon as we set up the handler.
# Normally you would not do this and the server
# would run forever or until it received instructions
# to stop.
self.handle_close()
return
def handle_close(self):
self.close()
为什么" EchoHandler(sock = client_info [0])"足够?创建的对象没有名称。如何调用EchoHandler对象中定义的方法?
答案 0 :(得分:0)
“EchoHandler(sock = client_info [0])”就足够了,因为在这个例子中不需要调用它。您只需将处理程序连接到客户端并忘记它。它将回答客户端本身的调用,并在客户端关闭时关闭。 如果你想稍后再打电话,就像jedwards写的一样。