Learning Python Network Programming

(Sean Pound) #1
Chapter 7

Then the client/server enters into the request/response loop. The client process
sends data to the server process, and the server process processes the data and
returns a response to the client. When the client process finishes, it exits by closing
down the connection. At that moment, the server process probably goes back to the
listening state.


The above interaction between client and server is a very simplified representation
of the actual reality. In practice, any production server process has multiple threads
or subprocesses to handle concurrent connections from thousands of clients over
respective virtual channels.


Working with TCP sockets


Creating a socket object in Python is very straightforward. You just need to import
the socket module and call the socket() class:


from socket import*
import socket

#create a TCP socket (SOCK_STREAM)
s = socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0)
print('Socket created')

Traditionally, the class takes plenty of parameters. Some of them are listed in
the following:



  • Socket family: This is the domain of socket, such as AF_INET (about
    90 percent of the sockets of the Internet fall under this category) or AF_UNIX,
    which is sometimes used as well. In Python 3, you can create a Bluetooth
    socket using AF_BLUETOOTH.

  • Socket type: Depending on your need, you need to specify the type of
    socket. For example, TCP and UDP-based sockets are created by specifying
    SOCK_STREAM and SOCK_DGRAM, respectively.

  • Protocol: This specifies the variation of protocol within a socket family
    and type. Usually, it is left as zero.


For many reasons, socket operations may not be successful. For example, if you
don't have permission to access a particular port as a normal user, you may not be
able to bind to a socket. This is why it is a good idea to do proper error handling
when creating a socket or doing some network-bound communication.

Free download pdf