simple communication between server and client using python
Requirements
Functions in the socket modul
In the below, the diagram has sequence of socket API and how to TCP data flow. We follow up the right-hand when we write server side. The left-hand shows client's steps.
https://www.keil.com/pack/doc/mw6/Network/html/using_network_sockets_bsd.html
The top of right-hand of diagram above is first several stages of socket_server.py. As you can see the beginning of server_connection function is creating a socket object. Also passed two parameters to this function, one of them is AF_INET and second is SOCK_STREAM. AF_INET is the Internet address family for IPv4. SOCK_STREAM is the socket type for TCP, the protocol that will be used to transport our messages in the network. Anyways, we now have a new socket object.
Like this: socket.socket(socket.AF_INET, socket.SOCK_STREAM)We get this socket() function so the first step for the server side. The next step is bind() function. Type of 2-Tuple host name and ports number is passed as parameters we defined at the top of socket_server.py.
We use in the code file for instance: soc.bind((host_address, port_number))
Now, there is need to listen ports thus we use listen() function like this soc.listen().
Before beginning the other with statement in the code, we define accept() function. This function provide connection and starts data loop. Also in this loop there are
two more functions recv() and send(). Also send() is used to as sendall() in while loop.
Getting the client socket object from accept() with connection that infinite loop is used to over connection.recv() function.
while True: data = connection.recv(1024) if not data: break connection.sendall(data)
Lastly start the server socket program with server_connection().
If you compare the client with the server you will see similar things probably and so simple according to server side. Now, the beginning of the client is same with server side. These four steps start with creating a socket object so:
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
The order of other steps is connect(), send() and recv(). Lastly, it calls soc.recv() to read the server’s reply and then prints it.
So, we use that recv() like this:
data = soc.recv(1024)
and start client_connection().