[英]Python socket wait for client connection
有沒有辦法停止while循環,直到客戶端連接到該服務器? 服務器應該為每個新的客戶端連接創建一個新線程,這可能嗎?
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")
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()
您在主循環中接受連接,然后將客戶端詳細信息傳遞給線程進行處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.