Creating a server and client with sockets

To create a socket, the socket.socket() constructor is used, which can take the family, type, and protocol as optional parameters. By default, the AF_INET family and the SOCK_STREAM type are used.

In this section, we will see how to create a couple of client and server scripts as an example.

The first thing we have to do is create a socket object for the server:

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

We now have to indicate on which port our server will listen using the bind method. For IP sockets, as in our case, the bind argument is a tuple that contains the host and the port. The host can be left empty, indicating to the method that you can use any name that is available.

The bind(IP,PORT) method allows you to associate a host and a port with a specific socket, taking into account that ports 1-1024 are reserved for the standard protocols:

server.bind(("localhost", 9999))

Finally, we use listen to make the socket accept incoming connections and to start listening. The listen method requires a parameter that indicates the number of maximum connections we want to accept.

The accept method keeps waiting for incoming connections, blocking execution until a message arrives.

To accept requests from a client socket, the accept() method should be used. In this way, the server socket waits to receive an input connection from another host:

server.listen(10)
socket_client, (host, port) = server.accept()

We can obtain more information about these methods with the help(socket) command:

Once we have this socket object, we can communicate with the client through it, using the recv and send methods (or recvfrom and sendfrom in UDP) that allow us to receive or send messages, respectively. The send method takes as parameters the data to send, while the recv method takes as a parameter the maximum number of bytes to accept:

received = socket_client.recv(1024)
print "Received: ", received
socket_client.send(received)

To create a client, we have to create the socket object, use the connect method to connect to the server, and use the send and recv methods we saw earlier. The connect argument is a tuple with host and port, exactly like bind:

socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_client.connect(("localhost", 9999))
socket_client.send("message")

Let's see a complete example. In this example, the client sends to the server any message that the user writes and the server repeats the received message.