在Python中使用select()方法进行客户端/服务器聊天

时间:2016-01-25 03:00:56

标签: python sockets select network-programming

我正在用Python编写客户端/服务器程序,一旦客户端和服务器通过套接字成功连接,它们就可以交换消息。以下是我的服务器和客户端代码。编译时,正确建立连接并成功发送消息,但是在收到另一方的响应之前,不能发送第二条消息。

例如:

客户发送:"您好,服务器!"

服务器发送:"我已收到您的消息,客户端!"

客户发送:"很好,这是另一个"

客户发送:"以及第二个!"

此时,服务器终端窗口收到了一条消息,上面写着"伟大的,这是另一个",但必须先收到此消息,然后再接收#34;第二个!&#34 ;. 我认为我的问题是我需要使用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()

2 个答案:

答案 0 :(得分:0)

我强烈建议您阅读并熟悉this文档,尤其是非阻塞套接字部分。

您的代码现在会在等待数据从用户到达时阻止。您希望指示程序等待来自套接字的数据,同时允许用户键入输入。

答案 1 :(得分:0)

请看以下示例: 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()

close()