Python: UDP 回显服务器异步;发送后套接字关闭
Python: UDP echo server asyncore ; socket closing after send
我正在尝试编写一个使用 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()
有什么想法吗?
谢谢
解决方案是使用 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()
我正在尝试编写一个使用 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()
有什么想法吗?
谢谢
解决方案是使用 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()