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.
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.