The API of the socket module

In this section, we will explore the key API provided by the socket module to achieve the same functionalities in the process described previously. As we have mentioned, the socket module comes built-in in any Python 3 distribution, so we can simply import the module into our program without having to run installation commands.

To create a socket, we will use the socket.socket() method, which returns a socket object. This object is what we will be working with during most of the process of implementing various communication protocols. Additionally, socket methods have the following methods that help us control the communication protocols:

  • socket.bind(): This method binds the calling socket to the address that is passed to the method. In our examples, we will be passing in a tuple containing the address of the host and the port for the communication channel.
  • socket.listen(): This method allows the server that we create to accept connections from potential clients. Another optional positive-integer parameter can be passed to the method, to specify the number of allowed unaccepted connections before the server refuses new connections. We will be using 5 as an arbitrary number for this method in our later examples.
  • socket.accept(): This method, as the name suggests, accepts a specific connection that the calling socket object has. This calling object has to first be bound to an address and listening for connections to call this method. In other words, this method is to be called after the two preceding methods. The method also returns a pair of values, (conn, address), with conn being the new socket object that has accepted the connection and is able to send and receive data, and address being the address on the other end of the connection (the client address).
  • socket.makefile(): This method returns a file object that is associated with the calling socket object. We will be using this method to create a file that contains the data sent from the accepted clients of our server. This file object will also need to be closed appropriately, using the close() method.
  • socket.sendall(): This method sends the data passed as a parameter to the calling socket object. We will use this method to send data back to the clients connected to our server. Note that this method takes in data in bytes, so we will be passing byte strings to this method in our examples.
  • socket.close(): This method marks the calling socket object as closed. After this point, all operations applied on the socket object will fail. This is to be used when we terminate our server.
..................Content has been hidden....................

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