How to do it...

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:

  1. Import the relevant Python modules:
import socket
import time
  1. Create a new socket using the given address, socket type, and protocol number:
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  1. Get the local machine name (host):
host=socket.gethostname()
  1. Set the port number:
port=9999
  1. Connect (bind) the socket to host and to port:
serversocket.bind((host,port))

  1. 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)
  1. Establish a connection:
while True:
  1. 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()
  1. The address and the port that is connected are printed out:
print ("Connected with[addr],[port]%s"%str(addr))
  1. currentTime is evaluated:
currentTime=time.ctime(time.time())+"
"
  1. The following statement sends data to the socket, returning the number of bytes sent:
clientsocket.send(currentTime.encode('ascii'))
  1. 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:

  1. Import the socket library:
import socket
  1. The socket object is then created:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  1. Get the local machine name (host):
host=socket.gethostname()
  1. Set the port number:
port=9999
  1. 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)).
  1. Now, close the connection and finally print out the connection time to the server:
s.close()
print ("Time connection server:%s"%tm.decode('ascii'))
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset