Lesson 04
Client Program
Build a Python client socket that connects to a server on this computer, sends one short request, reads the reply, and closes the client socket.
Build a Python client socket that connects to a server on this computer, sends one short request, reads the reply, and closes the client socket.
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("Jordan".encode())
print(client.recv(1024).decode())
finally:
client.close()
worker.join()The client sends Jordan and prints Desk Jordan. connect uses the same host and port the server bound. send takes bytes from encode(). recv(1024).decode() is the reply text. The client socket closes in finally. This client does not call bind or listen. The server half is in the same file so the example can finish; in two programs the client file would contain socket, connect, send, recv, and close. The playground shows those bytes and the address tuple without calling connect, because a connect with no server would wait.
Key takeaways
- Create a client socket, then
connectto the server address sendthe request as bytesrecv(1024).decode()is the reply text- Close the client socket when the reply has been read
- The client in this lesson does not bind or listen
- Next: Database Communication — tables, a cursor, and SQL queries
- Previous: Server Program
Loading playground…
Check your understanding
Client Program Quiz
Which call reaches the server?
1 / 10