Sockets are the lead pipes of computer networks: they let you connect with other devices so that information can flow freely. As you might expect, they're widely used on the Internet. Peyton McCullough explains how to code sockets in Python.
Using sockets in Python is quite easy. Open up your Python command line, and let’s get to some code.
The first thing we must do is import the socket library:
>>> import socket
The socket library contains all the tools we need to work with sockets. The next thing we need to do is create a socket. This is simple. Execute the following code:
This creates a stream socket. You can also work with datagrams by replacing SOCK_STREAM with SOCK_DGRAM. A socket stream is where there is a constant connection between the client and server that stays alive until it is closed, and both the client and the server know if the connection is still alive. With datagrams, however, that is not the case. The connection is not kept alive, and your data might not even be received. Although datagrams can sound like a bad idea at first, they have their purposes. It might be easier and faster to use datagrams in certain situations.
Writing a Simple Server
Let’s write a simple server. If you’ll remember, a server is anything that receives connections from other computers, clients. Create a new Python file named server.py and insert the following code into it:
That’s quite a mouthful, so let’s split it up into something we can understand. The first two lines should already look familiar. We create a new socket to use. In the third line, we open port 2727 for connections.
To understand what a port is, let’s go back to our analogy. Picture the pump machine with thousands of pipes leading in and out of it. Each pipe would be a port, and clients would have the option of connecting to different ports. However, each port would be different – some might pump out green water, and others might pump out orange water.
The next line tells our socket to wait, or listen, for clients. Following that, there is an infinite loop. In this loop, we accept client connections, print out the client's address, print out the client's message and finally send a message back, closing the connection when we're done.