Python:UDP echo服务器asyncore;插件发送后关闭

时间:2017-05-26 12:44:07

标签: python sockets asyncore

我试图编写一个使用asyncore.dispatcher_with_send回显数据的UDP服务器

我遇到的问题是,当我设置缓冲区并调用self.send(self.buffer)时,它似乎调用handle_close并关闭套接字。

import asyncore, socket,

class Server(asyncore.dispatcher_with_send): 

def __init__(self):
    asyncore.dispatcher.__init__(self)
    self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.bind(('192.168.0.10', 1452))
    self.buffer = ''
    self.recvData = ''


def handle_close(self):
    self.close()

def handle_read(self):
    print self.recv(8192)
    self.buffer ='a'

def handle_write(self):
    if self.buffer != '':
        sent = self.send(self.buffer)
        self.buffer = self.buffer[sent:]


if __name__ == '__main__':

The_Server = Server()
asyncore.loop()

任何想法?

由于

1 个答案:

答案 0 :(得分:0)

解决方案是使用sendto并确保sendto地址是显式的。

import asyncore, socket,

class Server(asyncore.dispatcher_with_send): 

def __init__(self):
    asyncore.dispatcher.__init__(self)
    self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.bind(('192.168.0.10', 1452))
    self.buffer = ''
    self.recvData = ''


def handle_close(self):
    self.close()

def handle_read(self):
    print self.recv(8192)
    self.buffer ='a'

def handle_write(self):
    if self.buffer != '':
        sent = self.sendto(self.buffer,('192.168.0.9',1452))
        self.buffer = self.buffer[sent:]


if __name__ == '__main__':

The_Server = Server()
asyncore.loop()