Creating an Echo Server
00:00 In the next few lessons, you’ll learn how to use the basic socket API to create a simple connection between two processes. This first example will be an echo server and a client to use it, meaning that the server is just going to echo back to the client any messages it receives. We’ll start with the server side of the process.
00:56 Future examples will obtain these values in a more realistic way. This number represents the localhost, a reference to the computer this is running on. This server will only accept connections from this computer.
If you’re sharing a system with other users, you might want to check with your system administrator what numbers you’re allowed to use. Socket is a resource Python can manage, so you can use a
with statement to open it, and you don’t need to use a
close statement. This creates the listening socket.
01:52 As you can probably guess, this binds the socket you just created to the host and port you want to listen to. This, too, does exactly what it says. It’s going to listen for a request to the server from this socket.
02:08 When the program gets to this line, it will pause, waiting to accept a connection. This is called blocking. No other processing on this program will take place until a connection is accepted. When a connection is accepted, the client and server negotiate a new port to use for their interaction.
02:42 Here again are the details of each step as the program was being written. Create the socket with a resource manager, binding the socket to the desired host and port, waiting for a connection, then accepting the connection and creating a new socket to handle the communication with the client at its address.
03:05 Phase two of the process is performed by the client, and you’ll see in the next lesson how that works. But once the connection is established, we’re up to phase three, exchanging data. From this server’s perspective, all it needs to do is read the data it receives, then send it back.
04:13 And again, this loops until the client closes the connection. So you open the new socket and then, in a loop, receive data from the socket, which the client will have sent, and then send all of that data back.
Become a Member to join the conversation.