How to setup Python socket server correctly

Viewed 74

I recently started learning Python but I came across a question. Why does my while True loop stops when I do socket.accept()

My code does that keeps printing 'HEY!!':

import socket


host = "0.0.0.0"  #<- Not the real port and ip, I have working ones...
port = 1234

s = socket.socket()
s.bind((host, port))
s.listen(5)

while True:

    print("HEY!!")

    '''
    connection, adress = s.accept()
    print("Got connection from: '" + str(adress[0]) + ":" + str(adress[1]) + "'")
    '''

My code that only prints 'HEY!!' once:

import socket


host = "0.0.0.0"  #<- Not the real port and ip, I have working ones...
port = 1234

s = socket.socket()
s.bind((host, port))
s.listen(5)

while True:

    print("HEY!!")

    connection, adress = s.accept()
    print("Got connection from: '" + str(adress[0]) + ":" + str(adress[1]) + "'")

And how can I solve that it keeps printing 'HEY!!' but also let the socket work?

Thanks for reading!

UPDATE:
It is working now, I am using threading to achieve it.
Do you have the same problem? -> Google: "Multiple while true loops threading python"
Thanks for everyone that helped me!

1 Answers

Why does my while True loop stops when I do socket.accept()

accept is a blocking operation. It waits until a client connects. It continues after the client has been connected and returns the socket for the new client connection.

My code that only prints 'HEY!!' once:

It will print HEY!! more than once if clients connect to your server and thus the blocking accept returns.

Related