The article that you have linked to provides enough information for you to create a client and server to do what you are asking.
Note: this answer focuses on the raw socket connections, for HTTP: see the answer by @ŽilvinasRudžionis
how [does] the server knows what the client asking for?
It doesn't. Atleast not intrinsically. Which is why you need to write the code to make it understand what the client it asking. The best part of the article to understand this is the Echo Server section.
To begin understanding you will want to follow this example.
# echo_server.py
import socket
host = '' # Symbolic name meaning all available interfaces
port = 12345 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, # See [1]
socket.SOCK_STREAM)
s.bind((host, port)) # Server claims the port
s.listen(1) # See [2]
conn, addr = s.accept() # This is code halting, everything
# will hold here and wait for a connection
print('Connected by', addr)
while True:
data = conn.recv(1024) # Receive 1024 bytes
if not data: break # If data is Falsey (i.e. no data) break
conn.sendall(data) # Send all data back to the connection
conn.close()
[1] [2]
# echo_client.py
import socket
host = socket.gethostname() # Server is running on the same host
port = 12345 # The same port as used by the server
s = socket.socket(socket.AF_INET, # See server code ([1])
socket.SOCK_STREAM)
s.connect((host, port)) # Initiate the connection
s.sendall(b'Hello, world') # Send some bytes to the server
data = s.recv(1024) # Receive some bytes back
s.close() # Close the connection
print('Received', repr(data)) # Print the bytes received
This gives you a basic framework to see what is going on. From here, you can add your own code to inspect the data and connections.
The most important part is the bit where you accept connections on the server. Here, you can check the data received and respond appropriately. For time
, the first example in the article shows how to do this.
#--snip--
import time
# Receive all data
while True:
data = conn.recv(1024)
if not data: break
# Now we can check the data and prepare the response
if data == "TIME":
return_data = (time.ctime(time.time()) + "\r\n").encode('ascii')
elif data == "REQUEST COUNT":
# Code to get request count
elif "MULTI" in data:
# Example: MULTI 2 3
data = data.split(" ") # Becomes ["MULTI", "2", "3"]
# Code to multiply the numbers
# Send the result back to the client
conn.sendall(return_data)
I have created a github gist for the time example that you can download and play with. It should work with both Python 2 and 3.
<script src="https://gist.github.com/alxwrd/b9133476e2f11263e594d8c29256859a.js"></script>