为什么不使用asyncore调用handle_read方法?

时间:2009-04-06 18:25:01

标签: python sockets packet

我正在尝试使用asyncore调度程序(下面的代码)通过数据包套接字进行proto-type send / recv。虽然我的handle_write方法被及时调用,但似乎没有调用handle_read方法。 loop()会经常调用可读方法,但我无法接收任何内容。我知道在eth0上收到了数据包,因为一个简单的tcpdump显示了传入的数据包。我错过了什么吗?



#!/usr/bin/python

import asyncore, socket, IN, struct

class packet_socket(asyncore.dispatcher):

    def __init__(self):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_PACKET, socket.SOCK_RAW)
        self.buffer = '0180C20034350012545900040060078910'
        self.socket.setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("%ds" % (len("eth0")+1,), "eth0"))

    def handle_close(self):
        self.close()

    def handle_connect(self):
        pass

    def handle_read(self):
        print "handle_read() called"
        data,addr=self.recvfrom(1024)
        print data
        print addr

    def readable(self):
        print "Checking read flag"
        return True

    def writable(self):
        return (len(self.buffer) > 0)

    def handle_write(self):
        print "Writing buffer data to the socket"
        sent = self.sendto(self.buffer,("eth0",0xFFFF))
        self.buffer = self.buffer[sent:]

c = packet_socket()

asyncore.loop()


提前致谢。

1 个答案:

答案 0 :(得分:1)

我终于在同事的帮助下完成了这项工作。这与将protocol参数传递给create_socket()方法有关。不幸的是,调度程序的create_socket()没有采用第三个参数 - 所以我必须修改我的packet_socket()构造函数以使用预先创建的协议作为ETH_P_ALL的协议(或者你的协议类型)希望得到)作为一个论点。编辑后的代码:



#!/usr/bin/python

import asyncore, socket, IN, struct

proto=3
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
s.bind(("eth0",proto))

class packet_socket(asyncore.dispatcher):

    def __init__(self,sock):
        asyncore.dispatcher.__init__(self,sock)
        #self.create_socket(socket.AF_PACKET, socket.SOCK_RAW,socket.htons(3))
        self.buffer = '0180C20034350012545900040060078910'
        self.socket.setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("%ds" % (len("eth0")+1,), "eth0"))

    def handle_close(self):
        self.close()

    def handle_connect(self):
        pass

    def handle_read(self):
        print "handle_read() called" 
    data,addr=self.recvfrom(1024)
        print data
        print addr

    def readable(self):
        print "Checking read flag" 
    return True

    def writable(self):
        return (len(self.buffer) > 0)

    def handle_write(self):
        print "Writing buffer data to the socket" 
    sent = self.sendto(self.buffer,("eth0",0xFFFF))
        self.buffer = self.buffer[sent:]

c = packet_socket(s)

asyncore.loop()


谢谢,