我在學習asyncore模塊。所以我決定開發一個聊天程序。我必須同時收聽網絡和廣播udp包。但問題出在用戶輸入消息時,用戶看不到其他用戶發送的其他消息。我該怎麼辦?我的代碼:異步循環和raw_input問題
#!/usr/bin/python
# -*- coding: utf-8 -*-
import asyncore
import socket
class Listener(asyncore.dispatcher):
def __init__(self, port):
asyncore.dispatcher.__init__(self)
self.port = port
self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.bind(('', self.port))
def handle_connect(self):
print "CONNECTED."
def handle_read(self):
data, addr = self.recvfrom(1024)
print str(addr) + " > " + data
def handle_write(self):
pass
class Sender(asyncore.dispatcher):
def __init__(self, port):
asyncore.dispatcher.__init__(self)
self.buffer = ""
self.port = port
self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
self.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.bind(('',0))
def handle_connect(self):
print "CONNECTED."
def handle_read(self):
pass
def handle_write(self):
if self.buffer != "":
sent = self.sendto(self.buffer, ('<broadcast>', self.port))
self.buffer = self.buffer[sent:]
def handle_close(self):
self.close()
def serve_forever(self):
asyncore.loop(count = 10)
if __name__ == "__main__":
Listener(50000)
sender = Sender(50000)
while True:
sender.serve_forever()
sender.buffer += raw_input("Message:")
你有沒有考慮[Twisted](http://www.twistedmatrix.com)? –
我想用asyncore解決這個問題,如果可能的話。 – voiceofthesoul
你能給我一個很好的理由嗎? –