Home > front end >  A text is sent by socket non-stop, in a loop, I wanted it to be sent only once
A text is sent by socket non-stop, in a loop, I wanted it to be sent only once

Time:05-23

I wrote a code that just send a pre-established text. I got it, but the text is sent endlessly, non-stop, I wanted it to be sent only once. How do I do it please?

Server

from socket import *
host = gethostname()
port = 8889

print(f'HOST: {host} , PORT {port}')
serv = socket(AF_INET, SOCK_STREAM)
serv.bind((host, port))
serv.listen(5)
while 1:
    con, adr = serv.accept()
    while 1:
        msg = con.recv(1024)
        print(msg.decode())

Client

from socket import *
host = gethostname()
port = 8889
cli = socket(AF_INET, SOCK_STREAM)
cli.connect((host, port))
while 1:
    msg = ("hi")
    cli.send(msg.encode())

The result does not stop printing the hi

CodePudding user response:

while 1: means: loop forever. The client will loop forever sending a message, there is no need for while 1: in the client.

You might also want to remove the while 1: from server at line 9 as the server will never exit the following loop at line 11.

In case you want the while loop to stop looping you could check for a state of something, you could replace the 1 with a boolean operator (either true/1 or false/0). Here are some Python boolean operators

  • Related