Project Overview
A simple TCP-based client-server demonstration: the server listens for connections, sends a greeting message, and cleanly closes the socket; the client connects, receives the message, and terminates—illustrating basic socket lifecycle and data exchange.
Server Implementation
Initializes and binds a socket, then listens for up to 5 connections:
import socket
s = socket.socket()
print("Socket successfully created!")
port = 56789
s.bind(("", port))
print(f"Socket binded to port {port}")
s.listen(5)
print("Socket is listening")
In the main loop, accepts each client, logs its address, sends a thank-you message, and closes the connection:
while True:
c, addr = s.accept()
print("Got connection from", addr)
message = "Thank you for connecting with us"
c.send(message.encode())
c.close()
Client Implementation
Creates a socket, connects to the server, receives the greeting, and prints it:
import socket
s = socket.socket()
port = 56789
s.connect(("127.0.0.1", port))
print(s.recv(1024))
s.close()
Demonstrates a single-request lifecycle: connect()
, recv()
, and close()
.
Key Takeaways
- Socket creation, binding, listening, and accepting connections.
- Data transmission through
send
andrecv
. - Proper connection teardown via
close()
.