0

I just made a simple program using sockets in python but when i receive and print the message this happens.

client.py code

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.0.108",1234))

while True:
    s.send(bytes("Hello","utf-8"))

server.py code

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0",1234))
s.listen(100)

while True:
    clientsocket, addr= s.accept()

    msg = clientsocket.recv(1024)
    msg = msg.decode("utf-8")
    print(msg)

output:

HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello```

I dont know why this is happening. I hope you guys can help!

Shashankh_
  • 149
  • 7
  • 1
    `while True:` makes your code repeat. Each time through the loop prints one `Hello`, but your loops run forever. (The top one sends as many `Hello`s as is can through a single socket; the bottom one receives as many sockets as it can and prints up to 1024 bytes from each; so the net result is that the bottom one runs only once, but the top one fills all 1024 bytes that the bottom one receives with `Hello`s). – Charles Duffy Nov 12 '21 at 15:13
  • for i in range(10): s.send(bytes("Hello","utf-8")) idk about socket so – Kirito-Kun Nov 12 '21 at 15:14
  • @CharlesDuffy i understand, but why do people use while loop for this then. i have seen a lot of youtubers using while loop. – Shashankh_ Nov 12 '21 at 15:22
  • @Shashankh_, the point of `while True` in the _server_ is to accept new connections after the first connection is done. The `while True` in the _client_ is just wrong, if you don't want the client to send `Hello` more than once. – Charles Duffy Nov 12 '21 at 15:47
  • (and in a real-world server that had longer-lived connections, you would probably fork off a thread for each one so new connections could come in while an existing one was still ongoing) – Charles Duffy Nov 12 '21 at 15:53
  • @CharlesDuffy I see.. thank you for your help. – Shashankh_ Nov 13 '21 at 02:17

0 Answers0