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

2024-04-26 04:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在我这里的聊天应用程序中,当客户端发送消息并将消息发送到服务器时,服务器必须先发送回复,然后客户端才能再次发送消息。如何避免这种情况

服务器程序:

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

Tags: fromimportclienttruehost消息客户端data
1条回答
网友
1楼 · 发布于 2024-04-26 04:21:28

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

不管怎样,根据你的实现方式,这里有一个方法:

服务器:

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

相关问题 更多 >