如何避免客户端和服务器之间的聊天应用程序出现以下差异?

时间:2016-06-20 12:56:42

标签: python multithreading python-2.7 sockets python-sockets

在我的聊天应用程序中,当客户端发送消息时向服务器发送消息,服务器必须在客户端再次发送消息之前发送回复。怎么避免这个?

服务器程序:

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

1 个答案:

答案 0 :(得分: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()