Search code examples
pythonsocketsasyncore

Python: UDP echo server asyncore ; socket closing after send


I'm trying to write a UDP server that echos data back using asyncore.dispatcher_with_send

The problem i have is that when i set the buffer and call self.send(self.buffer), it seems to call handle_close and closes the socket.

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()

Any Ideas?

Thanks


Solution

  • The solution was to use sendto and to make sure the sendto address was explicit.

    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()