Lesson 03
Server Program
Build a Python server socket that binds to this computer, accepts one client, reads a short request, sends one reply, and closes both sockets.
Build a Python server socket that binds to this computer, accepts one client, reads a short request, sends one reply, and closes both sockets.
Example
import socket
import threading
def serve(ready):
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 5050))
server.listen(1)
ready.append(5050)
server.settimeout(3)
client, address = server.accept()
try:
message = client.recv(1024).decode()
print("request", message, "from", address[0])
client.send(("Desk " + message).encode())
finally:
client.close()
server.close()
ready = []
worker = threading.Thread(target=serve, args=(ready,))
worker.start()
while not ready:
worker.join(0.01)
client = socket.socket()
try:
client.connect(("127.0.0.1", 5050))
client.send("Avery".encode())
print(client.recv(1024).decode())
finally:
client.close()
worker.join()The server prints request Avery from 127.0.0.1, and the client prints Desk Avery. bind uses this computer only. listen(1) queues one waiting client. accept returns the connection and the address pair. The reply is encoded before send. Both sockets close in finally. The server function runs on a thread only so this one file can also run the client and then exit. Two real programs would be two files, with the same bind, listen, accept, recv, and send steps. The playground does not call accept, because that call waits. It shows the same request and reply as bytes.
Key takeaways
-
Import
socket, create the server socket, thenbindandlisten -
acceptwaits for one client and returns the connection plus the address -
recv(1024).decode()is the request text -
sendthe reply only afterencode() -
Close the client socket and the server socket
-
Next: Client Program — connect, send one request, and read the reply
-
Previous: Socket Calls
Loading playground…
Check your understanding
Server Program Quiz
Which sequence prepares the server before a client arrives?
1 / 10