0

有沒有辦法停止while循環,直到客戶端連接到此服務器? 服務器shuld爲每個新客戶端連接創建一個新線程,這有可能嗎?Python套接字等待客戶端連接

import socket 
import threading 

def clientdialog(myS): 
    conn, addr = myS.accept() 
    print ("Connection from: " + str(addr)) 

    while 1: 
       data = conn.recv(1024).decode("utf-8") 
       if not data or data == 'q': 
        break 
       print ("from connected user: " + str(data)) 

host = "192.168.1.3" 
port = 1998 

mySocket = socket.socket() 
mySocket.bind((host,port)) 

while True: 

    mySocket.listen(10) 
    #whait until socket don't connect 

    try: 
     threading._start_new_thread(clientdialog, (mySocket)) 
    except: 
     print("error starting thread") 

回答

2

socket.listen函數被調用一次,因爲它設置了連接隊列的大小。

另一個稱爲socket.accept的函數會阻塞直到建立連接。修改您的代碼是這樣的:

mySocket = socket.socket() 
mySocket.bind((host,port)) 
mySocket.listen(10) 

while True: 
    client_socket, client_address = mySocket.accept() # blocking call 
    .... # do something with the connection 

欲瞭解更多信息,請訪問docs

此外,您希望將客戶端套接字的詳細信息傳遞給該線程。服務器套接字不是必需的。實際上,如下所示:

def handle_client(client_socket, client_address): 
    .... # do something with client socket 
    client_socket.close() 

... 

while True: 
    client_socket, client_address = mySocket.accept() 
    T = threading.Thread(target=handle_client, args=(client_socket, client_address)) 
    T.start() 

您接受主循環中的連接,然後將客戶端詳細信息傳遞給線程進行處理。

+0

線程部分不工作,但阻擋呼叫完美,謝謝 – Racerider

+0

@Racerider很高興我能幫上忙。我在這裏寫的代碼是一個有代表性的例子。有幾個補充它應該工作。祝一切順利。 –