我在python(2.7.8)中遇到线程问题。问题出在一个python" chat"编写的代码(我将代码包含在我的线程类和我的客户端类(不同的python文件)中,因为我认为这个问题出现在其中一个中,而不是在服务器代码中)。当我运行Client.py文件时,我能够通过服务器与另一个客户端(运行相同的python代码)进行通信,但问题是我必须刷新.send_payload(msg)命令才能接收消息另一个客户已发送(或只是通过按下输入聊天,然后发送""作为消息)。我想知道是否有可能在没有"刷新"聊天,不知何故通过线程。
class MessageReceiver(Thread):
def __init(self,client,connection):
Thread.__init__(self)
self.daemon = True
self.client = client
self.connection = connection
self.stop = False
def run(self):
while not self.stop:
data = self.connection.recv(8192)
if not data:
break
else:
self.client.receive_message(data)
pass
class Client:
def __init__(self, host, server_port):
self.host = host
self.server_port = server_port
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.run()
def run(self):
self.connection.connect((self.host, self.server_port))
self.thread = MessageReceiver(self, self.connection)
self.thread.start()
while True:
text = raw_input()
if(text.find("login") == 0):
data={"request":"login","content":text[text.find("login")+6:]}
self.send_payload(data)
if(text.find("names") == 0):
data={"request":"names","content":""}
self.send_payload(data)
else:
data={"request":"msg","content":text}
self.send_payload(data)
def disconnect(self):
self.thread.stop = True
self.connection.close()
print("Disconnected")
def receive_message(self, message):
print("Msg: " + message)
def send_payload(self, data):
self.connection.send(json.dumps(data))
print("Payload sent!")