Clients and Servers
Client-server is a split of work where a client asks and a server answers. A phone app, a browser and a game can all act as clients.
One request, one response
The client sends one request. The server function returns the response.
def server(request):
return "Here is the " + request
print("request: photo page")
print("response:", server("photo page"))Requests and responses stay in order
Three requests arrive in a fixed order. Each response follows the request that caused it.
def server(request):
return "Here is the " + request
requests = ["home page", "photo page", "profile page"]
for request in requests:
print("request:", request)
print("response:", server(request))One server, many clients
Two clients ask the same server for a greeting. The one server answers both clients in turn.
def server(name):
return "Hello, " + name
clients = [("Ana phone", "Ana"), ("Ben laptop", "Ben")]
for device, name in clients:
print(device, "asks for a greeting")
print("server answers:", server(name))Example
prices = {"milk": 3, "bread": 2, "eggs": 5}
def shop_server(request):
return "price of " + request + " is " + str(prices[request]) + " dollars"
requests = ["milk", "bread", "eggs"]
for request in requests:
print("request:", request)
print("response:", shop_server(request))
print("requests answered:", len(requests))Key points
- Client: the program that asks for something.
- Server: the program that builds the answer.
- Client-server: the split where clients ask and a server answers.
- Request: the message a client sends to ask.
- Response: the message a server sends back with the answer.
In this example, a shop server answers three price requests in order. Each response carries the price for the item in its request, so the pairs line up.
Note
many clients can share one server at the same time.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In a client-server setup, which side builds the answer?