在我这里的聊天应用程序中,当客户端发送消息并将消息发送到服务器时,服务器必须先发送回复,然后客户端才能再次发送消息。如何避免这种情况
服务器程序:
from socket import *
import threading
host=gethostname()
port=7776
s=socket()
s.bind((host, port))
s.listen(5)
print "Server is Ready!"
def client():
c, addr= s.accept()
while True:
print c.recv(1024)
c.sendto(raw_input(), addr)
for i in range(1,100):
threading.Thread(target=client).start()
s.close()
客户端程序:
from socket import *
host=gethostname()
port=7776
s=socket()
s.connect((host, port))
while True:
s.send(( raw_input()))
data= s.recv(1024)
if data:
print data
s.close()
我很确定您的目的是让中央服务器接收来自客户端的消息,并将它们发送给所有其他客户端,不是吗?您实现的并不完全是这样—相反,服务器进程只是打印从客户机到达的所有消息
不管怎样,根据你的实现方式,这里有一个方法:
服务器:
客户端:
相关问题 更多 >
编程相关推荐