简体   繁体   English

Python套接字等待客户端连接

[英]Python socket wait for client connection

Is there a way to stop the while loop until the clients connect to this server? 有没有办法停止while循环,直到客户端连接到该服务器? The server shuld create a new thread for each new client connection, it is possible? 服务器应该为每个新的客户端连接创建一个新线程,这可能吗?

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")

The socket.listen function is to be called once, because it sets the size of the connection queue. socket.listen函数将被调用一次,因为它设置了连接队列的大小。

Another function called socket.accept will block until connections are made. 另一个名为socket.accept函数将阻塞,直到建立连接为止。 Modify your code like this: 像这样修改您的代码:

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

For more information, visit the docs . 有关更多信息,请访问docs

Additionally, you'd want to pass the details of the client socket to the thread. 另外,您希望将客户端套接字的详细信息传递给线程。 The server socket isn't required. 不需要服务器套接字。 In effect, something like this: 实际上,是这样的:

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()

You accept the connection in the main loop, then pass the client details to the thread for processing. 您在主循环中接受连接,然后将客户端详细信息传递给线程进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM