Racerider
Racerider

Reputation: 116

Python socket wait for client connection

Is there a way to stop the while loop until the clients connect to this server? 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")

Upvotes: 0

Views: 6408

Answers (1)

cs95
cs95

Reputation: 402483

The socket.listen function is to be called once, because it sets the size of the connection queue.

Another function called socket.accept will block until connections are made. 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.

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.

Upvotes: 3

Related Questions