In this repo we learn socket programming in python using an online guide.
First, we import the socket module and define a hostname and port number.
We then create a socket object and bind it to the port number using with to automatically close the socket when the block is exited
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((hostname, port))
The constants socket.AF_INET and socket.SOCK_STREAM are used to specify the address family (IPv4) and socket type (TCP) respectively.
Next, we start listening for incoming connections using listen(). The accept() method blocks execution until a connection is established.
This will create a new listening socket and return a tuple (for IPv4) containing the new socket connection object and the address of the client.
s.listen()
conn, addr = s.accept()
After accepting the connection, we can send and receive data using the send() and recv() methods.
In this example we use an infinite while loop to loop over blocking calls to conn.recv().
This reads whatever data the client sends and echoes it back using conn.sendall().
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
If the conn.recv() returns an empty bytes object, b' ', then the client has disconnected and the loop closes.