1

就像在我的聊天应用程序中一样,当客户端发送一条消息时,它会向服务器发送一条消息,服务器必须先发送回复,然后客户端才能再次发送消息。如何避免这种情况?

服务器程序:

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

1 回答 1

0

我很确定你的意思是让中央服务器接收来自客户端的消息,并将它们发送给所有其他客户端,不是吗?您实现的并不完全是那样 - 相反,服务器进程只是打印从客户端到达的所有消息。

无论如何,根据您实现它的方式,这是一种方法:

服务器:

from socket import *
import threading

def clientHandler():
    c, addr = s.accept()
    c.settimeout(1.0)

    while True:
        try:
            msg = c.recv(1024)
            if msg:
                print "Message received from address %s: %s" % (addr, msg)
        except timeout:
            pass

host = "127.0.0.1"
port = 7776
s = socket()
s.bind((host, port))
s.listen(5)

for i in range(1, 100):
    threading.Thread(target=clientHandler).start()
s.close()
print "Server is Ready!"

客户

from socket import *

host = "127.0.0.1"
port = 7776

s = socket()
s.settimeout(0.2)

s.connect((host, port))

print "Client #%x is Ready!" % id(s)

while True:
    msg = raw_input("Input message to server: ")
    s.send(msg)

    try:
        print s.recv(1024)
    except timeout:
        pass

s.close()
于 2016-06-20T13:17:00.543 回答