I'm trying to implement a loop for this socket code, but I can't quite seem to wrap my head around it. Is anyone able to explain it for me?
Here's the code
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
Toto
91.7k63 gold badges97 silver badges135 bronze badges
asked Jun 8, 2021 at 4:35
user15219769
-
1A loop for what purpose? To just send, recv, and print? If so, then don't you think send, recv, and print need to be in a loop? I'm not sure where you are confused.Tim Roberts– Tim Roberts2021年06月08日 04:43:24 +00:00Commented Jun 8, 2021 at 4:43
1 Answer 1
Do you possible mean this?
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True:
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
answered Jun 8, 2021 at 4:43
Tim Roberts
55.3k4 gold badges29 silver badges41 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py