Socket programming basics

When we talk of sockets, we are referring to both the TCP and the UDP socket. A socket connection is nothing but a combination of the IP address and the port number. Every service that we can think of that runs on a port implements and uses sockets internally.

For example, our web server, which always listens on port 80 (by default), opens a socket connection to the outside world and binds to the socket with the IP address and the port 80. The socket connection can be used in the following two modes:

  • Server
  • Client

When the socket is used as a server, the sequence of steps that the server performs is as follows:

  1. Create a socket.
  2. Bind to the socket.
  3. Listen at the socket.
  4. Accept connections.
  5. Receive and send data.

On the other hand, when the socket connection is used as a client to connect to a server socket, the sequence of steps is as follows:

  1. Create a socket.
  2. Connect to the socket.
  3. Receive and send data.

Take a look at the following code snippet server_socket.py, which implements a TCP server socket at port 80:

In the preceding case, we created a socket with the socket.socket statement. Here, socket.AF_INET represents the IPv4 protocol and socket.SOCK_STREAM suggests the use of stream-based socket packets, which are nothing but TCP streams. The bind() method takes a tuple as an argument, with the first argument being the local IP address. You should replace this with your personal IP, or 127.0.0.1. The second parameter that is given to tuple is the port, which in turn calls the bind() method. We then start listening on the socket and finally start a loop where we accept client connections. Note that the method creates a single-threaded server, which means that if any other client connects, it has to wait until the active client is disconnected. The send () and recv() methods are self-explanatory.

Let's now create a basic client socket code ,client_socket.py, that connects to the previously created servers and passes messages to it:

The output produced by both the client and server sockets is as follows:

This is how we use a socket connection with UDP:

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
..................Content has been hidden....................

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