我正在用 Python 编写一个客户端/服务器程序,一旦客户端和服务器通过套接字成功连接,它们就可以交换消息。下面是我的服务器和客户端代码。编译时,连接正确建立,消息发送成功,但无法发送第二条消息,直到收到对方的响应。
例如:
客户端发送:“你好,服务器!”
服务器发送:“客户端,我收到你的消息了!”
客户端发送:“太好了,这是另一个”
客户端发送:“还有第二个!”
此时,服务器终端窗口已经收到消息说“太好了,这是另一个”,但必须先回复此消息才能收到“还有第二个!”。 我认为我的问题是我需要使用 select() 方法,但不明白如何使用。我该如何解决这个问题?
#The server code
HOST = ''
PORT = 9999
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
print("Now listening...")
s.listen(1) #only needs to receive one connection (the client)
conn, addr = s.accept() #accepts the connection
print("Connected by: ", addr) #prints the connection
i = True
while i is True:
data = conn.recv(1024) #receives data
print('Received:' , repr(data)) #prints the message from client
reply = raw_input() #server types a response
conn.sendall(reply) #server now sends response back to client
close()
下面是客户端代码(client.py)
客户端代码
from socket import*
HOST = '192.168.41.1'
PORT = 9999
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT))
while True:
message = raw_input() #client's message to the server
s.send(message) #sends message to the server
print("Waiting for response...")
reply = s.recv(1024) #receives message from server
print("New message: " + repr(reply)) #prints the message received
close()
最佳答案
看下面的例子: http://code.activestate.com/recipes/531824-chat-server-client-using-selectselect/
和 http://www.binarytides.com/code-chat-application-server-client-sockets-python/
这里也有一些类似的答案: Python client side in chat
您缺少的是在客户端进行选择,其中选择是处理来自服务器还是来自命令行的输入。
所以在这种情况下,您不必等待服务器响应,可以从客户端接连发送 2 个调用。
根据您希望完成的目标自由调整上述答案。 (我没有测试它 - 所以一定要检查它)
from socket import*
import sys
import select
HOST = '192.168.41.1'
PORT = 9999
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT))
while True:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(
socket_list, [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == s:
data = sock.recv(1024)
if not data:
print('\nDisconnected from server')
break
else:
#print data
sys.stdout.write(data)
# prints the message received
print("New message: " + repr(data))
prompt()
#user entered a message
else:
msg = sys.stdin.readline()
s.send(msg)
prompt()
s.close()
关于python - 在 Python 中使用 select() 方法进行客户端/服务器聊天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34984443/