In the following example, the server is listening on a default port, and by following a TCP/IP connection, the client sends to the server the date and time that the connection was established.
Here is the server implementation for server.py:
- Import the relevant Python modules:
import socket
import time
- Create a new socket using the given address, socket type, and protocol number:
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
- Get the local machine name (host):
host=socket.gethostname()
- Set the port number:
port=9999
- Connect (bind) the socket to host and to port:
serversocket.bind((host,port))
- Listen for connections made to the socket. The argument of 5 specifies the maximum number of connections in the queue. The maximum value depends on the system (usually, it is 5) and the minimum value is always 0:
serversocket.listen(5)
- Establish a connection:
while True:
- Then, the connection is accepted. The return value is a pair (conn, address), where conn is a new socket object that is used to send and receive data, and address is the address linked to the socket. Once accepted, a new socket is created and it will have its own identifier. This new socket is only used with this particular client:
clientsocket,addr=serversocket.accept()
- The address and the port that is connected are printed out:
print ("Connected with[addr],[port]%s"%str(addr))
- currentTime is evaluated:
currentTime=time.ctime(time.time())+" "
- The following statement sends data to the socket, returning the number of bytes sent:
clientsocket.send(currentTime.encode('ascii'))
- The following statement indicates the socket closure (that is, the communication channel); all subsequent operations on the socket will fail. The sockets are automatically closed when they are rejected, but it is always recommended to close them with the close() operation:
clientsocket.close()
The code for the client (client.py) is as follows:
- Import the socket library:
import socket
- The socket object is then created:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
- Get the local machine name (host):
host=socket.gethostname()
- Set the port number:
port=9999
- Set up the connection to host and port:
s.connect((host,port))
The maximum number of bytes that can be received is no more than 1,024 bytes: (tm=s.recv(1024)).
- Now, close the connection and finally print out the connection time to the server:
s.close()
print ("Time connection server:%s"%tm.decode('ascii'))