1

I want to ask you about while loop in socket works. The problem is, when i started app, the server is waiting for connections by While True. But if anyone connect, server won't accept another connections. The While True loop freezes.

My Code:

import socket
import threading

class Server(object):

    def __init__(self, host="localhost", port=5335):
        """Create socket..."""
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind((self.host, self.port))
        self.sock.listen(0)
        self.clients = []
        print("Server is ready to serve on adress: %s:%s..."%(self.host, self.port))

        while True:
            client, addr = self.sock.accept()
            print("There is an connection from %s:%s..."%addr)

            t = threading.Thread(target=self.threaded(client, addr))
            t.daemon = True
            t.start()

        self.sock.close()

    def threaded(self, client, adress):
        """Thread client requests."""
        while True:
            data = client.recv(1024)
            print("%s:%s : %s"%(adress[0], adress[1], data.decode('ascii')))
            if not data:
                print("Client %s:%s disconnected..."%adress)
                break

if __name__ == "__main__":
    Server()

1 Answer 1

1

You aren't calling the thread properly. You're calling self.threaded(client, addr) immediately and then passing the result to threading.Thread().

In other words, this:

t = threading.Thread(target=self.threaded(client, addr))

... is identical to this:

result = self.threaded(client, addr)
t = threading.Thread(target=result)

You need to call it like this:

t = threading.Thread(target=self.threaded, args=(client, addr))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.