Python套接字编程序列查询

 收藏

我正在尝试将来自客户端的查询发送到基本服务器,然后将其转发到该基本服务器所连接的另外2个服务器。

(那两个服务器在其数据库中找到与查询匹配的内容,如果匹配,则将查询发回,如果不匹配,则不发送任何内容)

首先,我将查询从基本服务器发送到名为ts1的第一台服务器,如果没有得到答复,则将其发送到名为ts2的第二台服务器。如果我也没有收到ts2的回复,则会向客户端发送错误主机消息。

我已经尝试了这些while和内部while循环来完成此任务,但是我的程序在发送第一个查询后挂起。因为ts1服务器在第一个查询上什么都不发送。

我该如何纠正我的代码,使其不会挂起并执行整个代码?也许它不阻塞或阻塞套接字?我不知道如何实现。

    while True:

        # receive a message from the client
        data_from_client = csockid.recv(1024)
        word = data_from_client.decode('utf-8').lower()

        if word == '':

            break

        print('[Client]: ' + word)
        print("[ls Server]: Sending " + word + " to ts1 & ts2 for Query....")

        ts1.send(word.encode('utf-8'))

        while True:

            search_from_ts1 = ts1.recv(1024)
            ts1_server_answer = search_from_ts1.decode('utf-8')

            print("[ls Server]: sending reply from ts1 server " + ts1_server_answer + " to Client")
            csockid.send(ts1_server_answer.encode('utf-8'))

            if not search_from_ts1:

                ts2.send(word.encode('utf-8'))

                while True:

                     search_from_ts2 = ts2.recv(1024)
                     ts2_server_answer = search_from_ts2.decode('utf-8')

                     print("[ls Server]: sending reply from ts2 server " + ts2_server_answer + " to Client")
                     csockid.send(ts2_server_answer.encode('utf-8'))

                     if not search_from_ts2:

                        print("[ls Server]: No match found in both ts1 & ts2")
                        error = " - Error:HOST NOT FOUND"
                        csockid.send(error.encode('utf-8'))

                        break
            break

        if not data_from_client:

            break

回复
  • Have a look at the non-blocking sockets section in https://docs.python.org/2/howto/sockets.html for reference. It tells you how to set up non-blocking sockets and the use of select to poll more than one socket.

  • You might want to set a timeout, then try the other server, but that might make the code unacceptably slow. At this point you might want to explore async functions which give you the instruments for doing this properly (sending the request to both servers "simultaneously" and then take whatever is available but have a timeout on both request replies).