编程语言
首页 > 编程语言> > python asyncore跟踪客户端

python asyncore跟踪客户端

作者:互联网

我正在编写一个简单的套接字服务器,并且想跟踪客户端状态(身份验证和内容).每次调用handle_read()时,我对该特定客户端一无所知.如果我知道客户端的ID或其他信息,这将有所帮助.这是我到目前为止的内容:

import asyncore
import socket

class EchoHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        data = self.recv(8192)
        self.send(data)

class EchoServer(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))
        self.listen(5)

    def handle_accept(self):
        pair = self.accept()
        if pair is None:
            pass
        else:
            sock, addr = pair
            print 'Incoming connection from %s' % repr(addr)
            handler = EchoHandler(sock)

server = EchoServer('localhost', 8080)
asyncore.loop()

解决方法:

从repr(addr)接收连接时,您确实知道客户端的ID.返回的元组是该客户端的IP和唯一编号,可在您要将数据发送回该客户端时使用.如果要保留客户列表,则应考虑使用字典,该字典在接收传入连接时会存储该客户的信息.

如果您希望将这些信息传递给handle_read函数,则您的代码将如下所示:

class EchoHandler(asyncore.dispatcher_with_send):
    def setAddr(self, addr):
        self.addr = addr

    def handle_read(self):
        data = self.recv(8192)
        print '%s from %s' % (data, self.addr)
        self.send(data)

class EchoServer(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))
        self.listen(5)

    def handle_accept(self):
        pair = self.accept()
        if pair is None:
            pass
        else:
            sock, addr = pair
            print 'Incoming connection from %s' % repr(addr)
            handler = EchoHandler(sock)
            handler.setAddr(addr) #Set the address of the sender in the EchoHandler

只需将客户端的地址发送到EchoHandler,现在您知道它的来源.希望这可以帮助/工作!

标签:asyncore,python,sockets
来源: https://codeday.me/bug/20191009/1881510.html