Sockets and the socket API are used to send messages across a network. They provide a form of inter-process communication (IPC). The network can be a logical, local network to the computer, or one that’s physically connected to an external network, with its own connections to other networks. The obvious example is the Internet, which you connect to via your ISP. Show
In this tutorial, you’ll create:
By the end of this tutorial, you’ll understand how to use the main functions and methods in Python’s socket module to write your own client-server applications. You’ll know how to use a custom class to send messages and data between endpoints, which you can build upon and utilize for your own applications. The examples in this tutorial require Python 3.6 or above, and have been tested using Python 3.10. To get the most out of this tutorial, it’s best to download the source code and have it on hand for reference while reading: Get Source Code: Click here to get the source code you’ll use for the examples in this tutorial. Networking and sockets are large subjects. Literal volumes have been written about them. If you’re new to sockets or networking, it’s completely normal if you feel overwhelmed with all of the terms and pieces. Don’t be discouraged though. This tutorial is for you! As with anything Python-related, you can learn a little bit at a time. Bookmark this article and come back when you’re ready for the next section. BackgroundSockets have a long history. Their use in 1971 and later became an API in the Berkeley Software Distribution (BSD) operating system released in 1983 called Berkeley sockets. When the Internet took off in the 1990s with the World Wide Web, so did network programming. Web servers and browsers weren’t the only applications taking advantage of newly connected networks and using sockets. Client-server applications of all types and sizes came into widespread use. Today, although the underlying protocols used by the socket API have evolved over the years, and new ones have developed, the low-level API has remained the same. The most common type of socket applications are client-server applications, where one side acts as the server and waits for connections from clients. This is the type of application that you’ll be creating in this tutorial. More specifically, you’ll focus on the socket API for Internet sockets, sometimes called Berkeley or BSD sockets. There are also Unix domain sockets, which can only be used to communicate between processes on the same host. Remove adsSocket API OverviewPython’s socket module provides an interface to the Berkeley sockets API. This is the module that you’ll use in this tutorial. The primary socket API functions and methods in this module are:
Python provides a convenient and consistent API that maps directly to system calls, their C counterparts. In the next section, you’ll learn how these are used together. As part of its standard library, Python also has classes that make using these low-level socket functions easier. Although it’s not covered in this tutorial, you can check out the socketserver module, a framework for network servers. There are also many modules available that implement higher-level Internet protocols like HTTP and SMTP. For an overview, see Internet Protocols and Support. TCP SocketsYou’re going to create a socket object using 7, specifying the socket type as 8. When you do that, the default protocol that’s used is the Transmission Control Protocol (TCP). This is a good default and probably what you want.Why should you use TCP? The Transmission Control Protocol (TCP):
In contrast, User Datagram Protocol (UDP) sockets created with 9 aren’t reliable, and data read by the receiver can be out-of-order from the sender’s writes.Why is this important? Networks are a best-effort delivery system. There’s no guarantee that your data will reach its destination or that you’ll receive what’s been sent to you. Network devices, such as routers and switches, have finite bandwidth available and come with their own inherent system limitations. They have CPUs, memory, buses, and interface packet buffers, just like your clients and servers. TCP relieves you from having to worry about packet loss, out-of-order data arrival, and other pitfalls that invariably happen when you’re communicating across a network. To better understand this, check out the sequence of socket API calls and data flow for TCP: TCP Socket Flow (Image source)The left-hand column represents the server. On the right-hand side is the client. Starting in the top left-hand column, note the API calls that the server makes to set up a “listening” socket:
A listening socket does just what its name suggests. It listens for connections from clients. When a client connects, the server calls 1 to accept, or complete, the connection.The client calls 2 to establish a connection to the server and initiate the three-way handshake. The handshake step is important because it ensures that each side of the connection is reachable in the network, in other words that the client can reach the server and vice-versa. It may be that only one host, client, or server can reach the other.In the middle is the round-trip section, where data is exchanged between the client and server using calls to 4 and 5.At the bottom, the client and server close their respective sockets. Remove adsEcho Client and ServerNow that you’ve gotten an overview of the socket API and how the client and server communicate, you’re ready to create your first client and server. You’ll begin with a simple implementation. The server will simply echo whatever it receives back to the client. Echo ServerHere’s the server:
Note: Don’t worry about understanding everything above right now. There’s a lot going on in these few lines of code. This is just a starting point so you can see a basic server in action. There’s a at the end of this tutorial that has more information and links to additional resources. You’ll also find these and other useful links throughout the tutorial. Okay, so what exactly is happening in the API call? 7 creates a socket object that supports the , so you can use it in a . There’s no need to call 0:
The arguments passed to are used to specify the and socket type. 2 is the Internet address family for IPv4. 3 is the socket type for , the protocol that will be used to transport messages in the network.The 9 method is used to associate the socket with a specific network interface and port number:
The values passed to 9 depend on the of the socket. In this example, you’re using 6 (IPv4). So it expects a two-tuple: 7. 8 can be a hostname, IP address, or empty string. If an IP address is used, 8 should be an IPv4-formatted address string. The IP address 00 is the standard IPv4 address for the loopback interface, so only processes on the host will be able to connect to the server. If you pass an empty string, the server will accept connections on all available IPv4 interfaces. 01 represents the number to accept connections on from clients. It should be an integer from 02 to 03, as 04 is reserved. Some systems may require superuser privileges if the port number is less than 05.Here’s a note on using hostnames with 9:
You’ll learn more about this later, in . For now, just understand that when using a hostname, you could see different results depending on what’s returned from the name resolution process. These results could be anything. The first time you run your application, you might get the address 07. The next time, you get a different address, 08. The third time, you could get 09, and so on.In the server example, 0 enables a server to accept connections. It makes the server a “listening” socket:
The method has a 12 parameter. It specifies the number of unaccepted connections that the system will allow before refusing new connections. Starting in Python 3.5, it’s optional. If not specified, a default 12 value is chosen.If your server receives a lot of connection requests simultaneously, increasing the 12 value may help by setting the maximum length of the queue for pending connections. The maximum value is system dependent. For example, on Linux, see 15.The method execution and waits for an incoming connection. When a client connects, it returns a new socket object representing the connection and a tuple holding the address of the client. The tuple will contain 7 for IPv4 connections or 18 for IPv6. See in the reference section for details on the tuple values.One thing that’s imperative to understand is that you now have a new socket object from 1. This is important because it’s the socket that you’ll use to communicate with the client. It’s distinct from the listening socket that the server is using to accept new connections:
After 1 provides the client socket object 21, an infinite 22 loop is used to loop over to 23. This reads whatever data the client sends and echoes it back using 24.If 23 returns an empty object, 27, that signals that the client closed the connection and the loop is terminated. The 9 statement is used with 21 to automatically close the socket at the end of the block.Remove adsEcho ClientNow let’s look at the client:
In comparison to the server, the client is pretty simple. It creates a socket object, uses to connect to the server and calls 31 to send its message. Lastly, it calls 32 to read the server’s reply and then prints it.Running the Echo Client and ServerIn this section, you’ll run the client and server to see how they behave and inspect what’s happening. Note: If you’re having trouble getting the examples or your own code to run from the command line, read How Do I Make My Own Command-Line Commands Using Python? or How to Run Your Python Scripts. If you’re on Windows, check the Python Windows FAQ. Open a terminal or command prompt, navigate to the directory that contains your scripts, ensure that you have Python 3.6 or above installed and on your path, then run the server:
Your terminal will appear to hang. That’s because the server is , or suspended, on 1:
It’s waiting for a client connection. Now, open another terminal window or command prompt and run the client:
In the server window, you should notice something like this:
In the output above, the server printed the 34 tuple returned from 35. This is the client’s IP address and TCP port number. The port number, 36, will most likely be different when you run it on your machine.Viewing Socket StateTo see the current state of sockets on your host, use 37. It’s available by default on macOS, Linux, and Windows.Here’s the netstat output from macOS after starting the server: 0Notice that 38 is 39. If 40 had used 41 instead of 42, netstat would show this: 1 38 is 44, which means all available host interfaces that support the address family will be used to accept incoming connections. In this example, 6 was used (IPv4) in the call to 8. You can see this in the 47 column: 48.The output above is trimmed to show the echo server only. You’ll likely see much more output, depending on the system you’re running it on. The things to notice are the columns 47, 38, and 51. In the last example above, netstat shows that the echo server is using an IPv4 TCP socket ( 48), on port 65432 on all interfaces ( 44), and it’s in the listening state ( 54).Another way to access this, along with additional helpful information, is to use 55 (list open files). It’s available by default on macOS and can be installed on Linux using your package manager, if it’s not already: 2 55 gives you the 57, 58 (process ID), and 59 (user ID) of open Internet sockets when used with the 60 option. Above is the echo server process. 37 and 55 have a lot of options available and differ depending on the OS that you’re running them on. Check the 63 page or documentation for both. They’re definitely worth spending a little time with and getting to know. You’ll be rewarded. On macOS and Linux, use 64 and 65. For Windows, use 66.Here’s a common error that you’ll encounter when a connection attempt is made to a port with no listening socket: 3Either the specified port number is wrong or the server isn’t running. Or maybe there’s a firewall in the path that’s blocking the connection, which can be easy to forget about. You may also see the error 67. Get a firewall rule added that allows the client to connect to the TCP port!There’s a list of common in the reference section. Remove adsCommunication BreakdownNow you’ll take a closer look at how the client and server communicated with each other: When using the loopback interface (IPv4 address 00 or IPv6 address 69), data never leaves the host or touches the external network. In the diagram above, the loopback interface is contained inside the host. This represents the internal nature of the loopback interface and shows that connections and data that transit it are local to the host. This is why you’ll also hear the loopback interface and IP address 00 or 69 referred to as “localhost.”Applications use the loopback interface to communicate with other processes running on the host and for security and isolation from the external network. Because it’s internal and accessible only from within the host, it’s not exposed. You can see this in action if you have an application server that uses its own private database. If it’s not a database used by other servers, it’s probably configured to listen for connections on the loopback interface only. If this is the case, other hosts on the network can’t connect to it. When you use an IP address other than 00 or 69 in your applications, it’s probably bound to an Ethernet interface that’s connected to an external network. This is your gateway to other hosts outside of your “localhost” kingdom:Be careful out there. It’s a nasty, cruel world. Be sure to read the section before venturing from the safe confines of “localhost.” There’s a security note that applies even if you’re not using hostnames but are using IP addresses only. Handling Multiple ConnectionsThe echo server definitely has its limitations. The biggest one is that it serves only one client and then exits. The echo client has this limitation too, but there’s an additional problem. When the client uses 32, it’s possible that it will return only one byte, 75 from 76: 4The 77 argument of 05 used above is the maximum amount of data to be received at once. It doesn’t mean that 5 will return 05 bytes.The 4 method also behaves this way. It returns the number of bytes sent, which may be less than the size of the data passed in. You’re responsible for checking this and calling 4 as many times as needed to send all of the data:
In the example above, you avoided having to do this by using 83:
You have two problems at this point:
What can you do? There are many approaches to concurrency. A popular approach is to use Asynchronous I/O. 87 was introduced into the standard library in Python 3.4. The traditional choice is to use threads.The trouble with concurrency is it’s hard to get right. There are many subtleties to consider and guard against. All it takes is for one of these to manifest itself and your application may suddenly fail in not-so-subtle ways. This isn’t meant to scare you away from learning and using concurrent programming. If your application needs to scale, it’s a necessity if you want to use more than one processor or one core. However, for this tutorial, you’ll use something that’s even more traditional than threads and easier to reason about. You’re going to use the granddaddy of system calls: . The 88 method allows you to check for I/O completion on more than one socket. So you can call 88 to see which sockets have I/O ready for reading and/or writing. But this is Python, so there’s more. You’re going to use the selectors module in the standard library so that the most efficient implementation is used, regardless of the operating system you happen to be running on:
Still, by using 88, you’re not able to run concurrently. That said, depending on your workload, this approach may still be plenty fast. It depends on what your application needs to do when it services a request, and the number of clients it needs to support. 87 uses single-threaded cooperative multitasking and an event loop to manage tasks. With 88, you’ll be writing your own version of an event loop, albeit more simply and synchronously. When using multiple threads, even though you have concurrency, you currently have to use the GIL (Global Interpreter Lock) with CPython and PyPy. This effectively limits the amount of work you can do in parallel anyway.This is all to say that using 88 may be a perfectly fine choice. Don’t feel like you have to use 87, threads, or the latest asynchronous library. Typically, in a network application, your application is I/O bound anyway: it could be waiting on the local network, for endpoints on the other side of the network, for disk writes, and so forth.If you’re getting requests from clients that initiate CPU bound work, look at the concurrent.futures module. It contains the class , which uses a pool of processes to execute calls asynchronously. If you use multiple processes, the operating system is able to schedule your Python code to run in parallel on multiple processors or cores, without the GIL. For ideas and inspiration, see the PyCon talk John Reese - Thinking Outside the GIL with AsyncIO and Multiprocessing - PyCon 2018. In the next section, you’ll look at examples of a server and client that address these problems. They use 88 to handle multiple connections simultaneously and call 4 and 5 as many times as needed.Remove adsMulti-Connection Client and ServerIn the next two sections, you’ll create a server and client that handles multiple connections using a 99 object created from the selectors module.Multi-Connection ServerFirst, turn your attention to the multi-connection server. The first part sets up the listening socket: 5The biggest difference between this server and the echo server is the call to 00 to configure the socket in non-blocking mode. Calls made to this socket will no longer . When it’s used with 01, as you’ll see below, you can wait for events on one or more sockets and then read and write data when it’s ready. 02 registers the socket to be monitored with 01 for the events that you’re interested in. For the listening socket, you want read events: 04.To store whatever arbitrary data you’d like along with the socket, you’ll use 05. It’s returned when 88 returns. You’ll use 05 to keep track of what’s been sent and received on the socket.Next is the event loop: 6until there are sockets ready for I/O. It returns a list of tuples, one for each socket. Each tuple contains a 09 and a 10. The 09 is a 12 that contains a 13 attribute. 14 is the socket object, and 10 is an event mask of the operations that are ready.If 16 is 84, then you know it’s from the listening socket and you need to accept the connection. You’ll call your own 18 function to get the new socket object and register it with the selector. You’ll look at that in a moment.If 16 is not 84, then you know it’s a client socket that’s already been accepted, and you need to service it. 21 is then called with 09 and 10 as arguments, and that’s everything you need to operate on the socket.Here’s what your 18 function does: 7Because the listening socket was registered for the event 04, it should be ready to read. You call 26 and then call 27 to put the socket in non-blocking mode.Remember, this is the main objective in this version of the server because you don’t want it to . If it blocks, then the entire server is stalled until it returns. That means other sockets are left waiting even though the server isn’t actively working. This is the dreaded “hang” state that you don’t want your server to be in. Next, you create an object to hold the data that you want included along with the socket using a . Because you want to know when the client connection is ready for reading and writing, both of those events are set with the operator: 8The 29 mask, socket, and data objects are then passed to 02.Now take a look at 21 to see how a client connection is handled when it’s ready: 9This is the heart of the simple multi-connection server. 09 is the 12 returned from 88 that contains the socket object ( 13) and data object. 10 contains the events that are ready.If the socket is ready for reading, then 37 will evaluate to 38, so 39 is called. Any data that’s read is appended to 40 so that it can be sent later.Note the 41 block to check if no data is received: 0If no data is received, this means that the client has closed their socket, so the server should too. But don’t forget to call 42 before closing, so it’s no longer monitored by 88.When the socket is ready for writing, which should always be the case for a healthy socket, any received data stored in 40 is echoed to the client using 45. The bytes sent are then removed from the send buffer: 1The 4 method returns the number of bytes sent. This number can then be used with on the 47 buffer to discard the bytes sent.Remove adsMulti-Connection ClientNow take a look at the multi-connection client, 48. It’s very similar to the server, but instead of listening for connections, it starts by initiating connections via 49: 2 50 is read from the command-line and is the number of connections to create to the server. Just like the server, each socket is set to non-blocking mode.You use instead of 2 because 2 would immediately raise a 54 exception. The 3 method initially returns an error indicator, 56, instead of raising an exception that would interfere with the connection in progress. Once the connection is completed, the socket is ready for reading and writing and is returned by 88.After the socket is set up, the data you want to store with the socket is created using 28. The messages that the client will send to the server are copied using 59 because each connection will call 60 and modify the list. Everything needed to keep track of what the client needs to send, has sent, and has received, including the total number of bytes in the messages, is stored in the object 05.Check out the changes made from the server’s 21 for the client’s version: 3It’s fundamentally the same but for one important difference. The client keeps track of the number of bytes it’s received from the server so that it can close its side of the connection. When the server detects this, it closes its side of the connection too. Note that by doing this, the server depends on the client being well-behaved: the server expects the client to close its side of the connection when it’s done sending messages. If the client doesn’t close, the server will leave the connection open. In a real application, you may want to guard against this in your server by implementing a timeout to prevent client connections from accumulating if they don’t send a request after a certain amount of time. Running the Multi-Connection Client and ServerNow it’s time to run 63 and 48. They both use command-line arguments. You can run them without arguments to see the options.For the server, pass 8 and 01 numbers: 4For the client, also pass the number of connections to create to the server, 67: 5Below is the server output when listening on the loopback interface on port 65432: 6Below is the client output when it creates two connections to the server above: 7Great! Now you’ve run the multi-connection client and server. In the next section, you’ll take this example even further. Remove adsApplication Client and ServerThe multi-connection client and server example is definitely an improvement compared with where you started. However, now you can take one more step and address the shortcomings of the previous 68 example in a final implementation: the application client and server.You want a client and server that handle errors appropriately so that other connections aren’t affected. Obviously, your client or server shouldn’t come crashing down in a ball of fury if an exception isn’t caught. This is something you haven’t had to worry about until now, because the examples have intentionally left out error handling for brevity and clarity. Now that you’re familiar with the basic API, non-blocking sockets, and 88, you can add some error handling and address the elephant in the room, which the examples have kept hidden from you behind that large curtain over there. Remember that custom class that was mentioned way back in the introduction? That’s what you’re going to explore next.First, you’ll address the errors:
So, one thing you need to do is catch 70. Another important consideration in relation to errors is timeouts. You’ll see them discussed in many places in the documentation. Timeouts happen and are a so-called normal error. Hosts and routers are rebooted, switch ports go bad, cables go bad, cables get unplugged, you name it. You should be prepared for these and other errors, handling them in your code.What about the elephant in the room? As hinted by the socket type 8, when using TCP, you’re reading from a continuous stream of bytes. It’s like reading from a file on disk, but instead you’re reading bytes from the network. However, unlike reading a file, there’s no .In other words, you can’t reposition the socket pointer, if there was one, and move around the data. When bytes arrive at your socket, there are network buffers involved. Once you’ve read them, they need to be saved somewhere, or else you will have dropped them. Calling 5 again reads the next stream of bytes available from the socket.You’ll be reading from the socket in chunks. So, you need to call 5 and save the data in a buffer until you’ve read enough bytes to have a complete message that makes sense to your application.It’s up to you to define and keep track of where the message boundaries are. As far as the TCP socket is concerned, it’s just sending and receiving raw bytes to and from the network. It knows nothing about what those raw bytes mean. This is why you need to define an application-layer protocol. What’s an application-layer protocol? Put simply, your application will send and receive messages. The format of these messages are your application’s protocol. In other words, the length and format that you choose for these messages define the semantics and behavior of your application. This is directly related to what you learned in the previous paragraph regarding reading bytes from the socket. When you’re reading bytes with 5, you need to keep up with how many bytes were read, and figure out where the message boundaries are.How can you do this? One way is to always send fixed-length messages. If they’re always the same size, then it’s easy. When you’ve read that number of bytes into a buffer, then you know you have one complete message. However, using fixed-length messages is inefficient for small messages where you’d need to use padding to fill them out. Also, you’re still left with the problem of what to do about data that doesn’t fit into one message. In this tutorial, you’ll learn a generic approach, one that’s used by many protocols, including HTTP. You’ll prefix messages with a header that includes the content length as well as any other fields you need. By doing this, you’ll only need to keep up with the header. Once you’ve read the header, you can process it to determine the length of the message’s content. With the content length, you can then read that number of bytes to consume it. You’ll implement this by creating a custom class that can send and receive messages that contain text or binary data. You can improve and extend this class for your own applications. The most important thing is that you’ll be able to see an example of how this is done. Before you get started, there’s something you need to know regarding sockets and bytes. As you learned earlier, when sending and receiving data via sockets, you’re sending and receiving raw bytes. If you receive data and want to use it in a context where it’s interpreted as multiple bytes, for example a 4-byte integer, you’ll need to take into account that it could be in a format that’s not native to your machine’s CPU. The client or server on the other end could have a CPU that uses a different byte order than your own. If this is the case, then you’ll need to convert it to your host’s native byte order before using it. This byte order is referred to as a CPU’s endianness. See in the reference section for details. You’ll avoid this issue by taking advantage of Unicode for your message header and using the encoding UTF-8. Since UTF-8 uses an 8-bit encoding, there are no byte ordering issues. You can find an explanation in Python’s documentation. Note that this applies to the text header only. You’ll use an explicit type and encoding defined in the header for the content that’s being sent, the message payload. This will allow you to transfer any data that you’d like (text or binary), in any format. You can easily determine the byte order of your machine by using 77. For example, you could see something like this: 8If you run this in a virtual machine that emulates a big-endian CPU (PowerPC), then something like this happens: 9In this example application, your application-layer protocol defines the header as Unicode text with a UTF-8 encoding. For the actual content in the message, the message payload, you’ll still have to swap the byte order manually if needed. This will depend on your application and whether or not it needs to process multi-byte binary data from a machine with a different endianness. You can help your client or server implement binary support by adding additional headers and using them to pass parameters, similar to HTTP. Don’t worry if this doesn’t make sense yet. In the next section, you’ll see how all of this works and fits together. Remove adsApplication Protocol HeaderNow you’ll fully define the protocol header. The protocol header is:
The required headers, or sub-headers, in the protocol header’s dictionary are as follows: NameDescription 78The byte order of the machine (uses 77). This may not be required for your application. 80The length of the content in bytes. 81The type of content in the payload, for example, 82 or 83. 84The encoding used by the content, for example, 85 for Unicode text or 86 for binary data.These headers inform the receiver about the content in the payload of the message. This allows you to send arbitrary data while providing enough information so that the content can be decoded and interpreted correctly by the receiver. Because the headers are in a dictionary, it’s easy to add additional headers by inserting key-value pairs as needed. Sending an Application MessageThere’s still a bit of a problem. You have a variable-length header, which is nice and flexible, but how do you know the length of the header when reading it with 5?When you previously learned about using 5 and message boundaries, you also learned that fixed-length headers can be inefficient. That’s true, but you’re going to use a small, 2-byte, fixed-length header to prefix the JSON header that contains its length.You can think of this as a hybrid approach to sending messages. In effect, you’re bootstrapping the message receive process by sending the length of the header first. This makes it easy for your receiver to deconstruct the message. To give you a better idea of the message format, check out a message in its entirety: A message starts with a fixed-length header of two bytes, which is an integer in network byte order. This is the length of the next header, the variable-length JSON header. Once you’ve read two bytes with 5, then you know you can process the two bytes as an integer and then read that number of bytes before decoding the UTF-8 JSON header.The contains a dictionary of additional headers. One of those is 80, which is the number of bytes of the message’s content (not including the JSON header). Once you’ve called 5 and read 80 bytes, then you’ve reached a message boundary, meaning you’ve read an entire message.Application Message ClassFinally, the payoff! In this section, you’ll study the 93 class and see how it’s used with 88 when read and write events happen on the socket.This example application reflects what types of messages a client and server could reasonably use. You’re far beyond toy echo clients and servers at this point! To keep things simple and still demonstrate how things would work in a real application, this example uses an application protocol that implements a basic search feature. The client sends a search request and the server does a lookup for a match. If the request sent by the client isn’t recognized as a search, the server assumes it’s a binary request and returns a binary response. After reading the following sections, running the examples, and experimenting with the code, you’ll see how things work. You can then use the 93 class as a starting point and modify it for your own use.The application is not that far off from the 68 client and server example. The event loop code stays the same in 97 and 98. What you’re going to do is move the message code into a class named 93 and add methods to support reading, writing, and processing of the headers and content. This is a great example for using a class.As you learned before and you’ll see below, working with sockets involves keeping state. By using a class, you keep all of the state, data, and code bundled together in an organized unit. An instance of the class is created for each socket in the client and server when a connection is started or accepted. The class is mostly the same for both the client and the server for the wrapper and utility methods. They start with an underscore, like 00. These methods simplify working with the class. They help other methods by allowing them to stay shorter and support the DRY principle.The server’s 93 class works in essentially the same way as the client’s and vice-versa. The difference is that the client initiates the connection and sends a request message, followed by processing the server’s response message. Conversely, the server waits for a connection, processes the client’s request message, and then sends a response message.It looks like this: StepEndpointAction / Message Content1ClientSends a 93 containing request content2ServerReceives and processes client request 933ServerSends a 93 containing response content4ClientReceives and processes server response 93Here’s the file and code layout: ApplicationFileCodeServer 98The server’s main scriptServer 07The server’s 93 classClient 97The client’s main scriptClient 10The client’s 93 classMessage Entry PointUnderstanding how the 93 class works can be a challenge because there’s an aspect of its design that might not be immediately obvious. Why? Managing state.After a 93 object is created, it’s associated with a socket that’s monitored for events using 14: 0Note: Some of the code examples in this section are from the server’s main script and 93 class, but this section and discussion applies equally to the client as well. You’ll be alerted when the client’s version differs.When events are ready on the socket, they’re returned by 16. You can then get a reference back to the message object using the 05 attribute on the 09 object and call a method in 93: 1Looking at the event loop above, you’ll see that 01 is in the driver’s seat. It’s blocking, waiting at the top of the loop for events. It’s responsible for waking up when read and write events are ready to be processed on the socket. Which means, indirectly, it’s also responsible for calling the method 21. That’s why 21 is the entry point.Here’s what the 21 method does: 2That’s good: 21 is simple. It can only do two things: call 25 and 26.This is where managing state comes in. If another method depended on state variables having a certain value, then they would only be called from 25 and 26. This keeps the logic as simple as possible as events come in on the socket for processing.You might be tempted to use a mix of some methods that check the current state variables and, depending on their value, call other methods to process data outside 25 or 26. In the end, this would likely prove too complex to manage and keep up with.You should definitely modify the class to suit your own needs so that it works best for you, but you’ll probably have the best results if you keep the state checks and the calls to methods that depend on that state to the 25 and 26 methods if possible.Now look at 25. This is the server’s version, but the client’s is the same. It just uses a different method name, 34 instead of 35: 3The 36 method is called first. It calls 37 to read data from the socket and store it in a receive buffer.Remember that when 37 is called, all of the data that makes up a complete message may not have arrived yet. 37 may need to be called again. This is why there are state checks for each part of the message before the appropriate method to process it is called.Before a method processes its part of the message, it first checks to make sure enough bytes have been read into the receive buffer. If they have, it processes its respective bytes, removes them from the buffer and writes its output to a variable that’s used by the next processing stage. Because there are three components to a message, there are three state checks and 40 method calls:Message ComponentMethodOutputFixed-length header 41 42JSON header 43 44Content 45 46Next, check out 26. This is the server’s version: 4The 26 method checks first for a 49. If one exists and a response hasn’t been created, 50 is called. The 50 method sets the state variable 52 and writes the response to the send buffer.The 53 method calls 60 if there’s data in the send buffer.Remember that when 60 is called, all of the data in the send buffer may not have been queued for transmission. The network buffers for the socket may be full, and 60 may need to be called again. This is why there are state checks. The 50 method should only be called once, but it’s expected that 53 will need to be called multiple times.The client version of 26 is similar: 5Because the client initiates a connection to the server and sends a request first, the state variable 60 is checked. If a request hasn’t been queued, it calls 61. The 62 method creates the request and writes it to the send buffer. It also sets the state variable 60 so that it’s only called once.Just like for the server, 53 calls 60 if there’s data in the send buffer.The notable difference in the client’s version of 26 is the last check to see if the request has been queued. This will be explained more in the section , but the reason for this is to tell 16 to stop monitoring the socket for write events. If the request has been queued and the send buffer is empty, then you’re done writing and you’re only interested in read events. There’s no reason to be notified that the socket is writable.To wrap up this section, consider this thought: the main purpose of this section was to explain that 16 is calling into the 93 class via the method 21 and to describe how state is managed.This is important because 21 will be called many times over the life of the connection. Therefore, make sure that any methods that should only be called once are either checking a state variable themselves, or the state variable set by the method is checked by the caller.Server Main ScriptIn the server’s main script 98, arguments are read from the command line that specify the interface and port to listen on: 6For example, to listen on the loopback interface on port 73, enter: 7Use an empty string for 74 to listen on all interfaces.After creating the socket, a call is made to 75 with the option 76: 8Setting this socket option avoids the error 77. You’ll see this when starting the server on a port that has connections in the TIME_WAIT state.For example, if the server actively closed a connection, it’ll remain in the 78 state for two minutes or more, depending on the operating system. If you try to start the server again before the 78 state expires, then you’ll get an 70 exception of 77. This is a safeguard to make sure that any delayed packets in the network aren’t delivered to the wrong application.The event loop catches any errors so that the server can stay up and continue to run: 9When a client connection is accepted, a 93 object is created: 0The 93 object is associated with the socket in the call to 02 and is initially set to be monitored for read events only. Once the request has been read, you’ll modify it to listen for write events only.An advantage of taking this approach in the server is that in most cases, when a socket is healthy and there are no network issues, it’ll always be writable. If you told 02 to also monitor 86, then the event loop would immediately wake up and notify you that this is the case. However, at this point, there’s no reason to wake up and call 4 on the socket. There’s no response to send, because a request hasn’t been processed yet. This would consume and waste valuable CPU cycles.Server Message ClassIn the section , you learned how the 93 object was called into action when socket events were ready via 21. Now you’ll learn what happens as data is read on the socket and a component, or piece, of the message is ready to be processed by the server.The server’s message class is in 07, which is part of the source code you downloaded earlier. You can also download the code by clicking the link below:Get Source Code: Click here to get the source code you’ll use for the examples in this tutorial. The methods appear in the class in the order in which processing takes place for a message. When the server has read at least two bytes, the fixed-length header can be processed: 1The fixed-length header is a 2-byte integer in network, or big-endian, byte order. It contains the length of the JSON header. You’ll use struct.unpack() to read the value, decode it, and store it in 42. After processing the piece of the message it’s responsible for, 92 removes it from the receive buffer.Just like with the fixed-length header, when there’s enough data in the receive buffer to contain the JSON header, it can be processed as well: 2The method 93 is called to decode and deserialize the JSON header into a dictionary. Because the JSON header is defined as Unicode with a UTF-8 encoding, 85 is hardcoded in the call. The result is saved to 44. After processing the piece of the message that it’s responsible for, 43 removes it from the receive buffer.Next is the actual content, or payload, of the message. It’s described by the JSON header in 44. When 80 bytes are available in the receive buffer, the request can be processed: 3After saving the message content to the 05 variable, 35 removes it from the receive buffer. Then, if the content type is JSON, 35 decodes and deserializes it. If it’s not, this example application assumes that it’s a binary request and simply prints the content type.The last thing 35 does is modify the selector to monitor write events only. In the server’s main script, 98, the socket is initially set to monitor read events only. Now that the request has been fully processed, you’re no longer interested in reading.A response can now be created and written to the socket. When the socket is writable, 50 is called from 26: 4A response is created by calling other methods, depending on the content type. In this example application, a simple dictionary lookup is done for JSON requests when 06. For your own applications, you can define other methods that get called here.After creating the response message, the state variable 07 is set so that 26 doesn’t call 50 again. Finally, the response is appended to the send buffer. This is seen by and sent via 53.One tricky bit to figure out is how to close the connection after the response is written. You can put the call to 6 in the method 53: 5Although it’s somewhat hidden, this is an acceptable trade-off given that the 93 class only handles one message per connection. After the response is written, there’s nothing left for the server to do. It’s completed its work.Client Main ScriptIn the client’s main script, 97, arguments are read from the command line and used to create requests and start connections to the server: 6Here’s an example: 7After creating a dictionary representing the request from the command-line arguments, the host, port, and request dictionary are passed to 15: 8A socket is created for the server connection, as well as a 93 object using the 49 dictionary.Like for the server, the 93 object is associated with the socket in the call to 02. However, for the client, the socket is initially set to be monitored for both read and write events. Once the request has been written, you’ll modify it to listen for read events only.This approach gives you the same advantage as the server: not wasting CPU cycles. After the request has been sent, you’re no longer interested in write events, so there’s no reason to wake up and process them. Client Message ClassIn the section , you learned how the message object was called into action when socket events were ready via 21. Now you’ll learn what happens after data is read and written on the socket and a message is ready to be processed by the client.The client’s message class is in 10, which is part of the source code you downloaded earlier. You can also download the code by clicking the link below:Get Source Code: Click here to get the source code you’ll use for the examples in this tutorial. The methods appear in the class in the order in which processing takes place for a message. The first task for the client is to queue the request: 9The dictionaries used to create the request, depending on what was passed on the command line, are in the client’s main script, 97. The request dictionary is passed as an argument to the class when a 93 object is created.The request message is created and appended to the send buffer, which is then seen by and sent via 53. The state variable 25 is set so that 61 isn’t called again.After the request has been sent, the client waits for a response from the server. The methods for reading and processing a message in the client are the same as for the server. As response data is read from the socket, the 40 header methods are called: 92 and 29.The difference is in the naming of the final 40 methods and the fact that they’re processing a response, not creating one: 34, 32, and 33.Last, but certainly not least, is the final call for 34: 0Message Class WrapupTo conclude your learning about the 93 class, it’s worth mentioning a couple of things that are important to notice with a few of the supporting methods.Any exceptions raised by the class are caught by the main script in the 36 clause inside the event loop: 1Note the line: 37.This is a really important line, for more than one reason! Not only does it make sure that the socket is closed, but 37 also removes the socket from being monitored by 88. This greatly simplifies the code in the class and reduces complexity. If there’s an exception or you explicitly raise one yourself, you know 6 will take care of the cleanup.The methods 41 and 42 also contain something interesting: 2Note the 43 line.The 53 method has one too. These lines are important because they catch a temporary error and skip over it using 45. The temporary error is when the socket would , for example if it’s waiting on the network or the other end of the connection, also known as its peer.By catching and skipping over the exception with 45, 88 will eventually trigger a new call, and you’ll get another chance to read or write the data.Remove adsRunning the Application Client and ServerAfter all of this hard work, it’s time to have some fun and run some searches! In these examples, you’ll run the server so that it listens on all interfaces by passing an empty string for the 8 argument. This will allow you to run the client and connect from a virtual machine that’s on another network. It emulates a big-endian PowerPC machine.First, start the server: 3Now run the client and enter a search. See if you can find him: 4You might notice that the terminal is running a shell that’s using a text encoding of Unicode (UTF-8), so the output above prints nicely with emojis. Now see if you can find the puppies: 5Notice the byte string sent over the network for the request in the 49 line. It’s easier to see if you look for the bytes printed in hex that represent the puppy emoji: 50. If your terminal is using Unicode with the encoding UTF-8, you’ll be able to enter the emoji for the search.This demonstrates that you’re sending raw bytes over the network and they need to be decoded by the receiver to be interpreted correctly. This is why you went to all of the trouble to create a header that contains the content type and encoding. Here’s the server output from both client connections above: 6Look at the 49 line to see the bytes that were written to the client’s socket. This is the server’s response message.You can also test sending binary requests to the server if the 52 argument is anything other than 53: 7Because the request’s 81 is not 82, the server treats it as a custom binary type and doesn’t perform JSON decoding. It simply prints the 81 and returns the first ten bytes to the client: 8TroubleshootingInevitably, something won’t work, and you’ll be wondering what to do. Don’t worry, it happens to everyone. Hopefully, with the help of this tutorial, your debugger, and your favorite search engine, you’ll be able to get going again with the source code part. If not, your first stop should be Python’s socket module documentation. Make sure you read all of the documentation for each function or method you’re calling. Also, read through the section below for ideas. In particular, check the section. Sometimes, it’s not all about the source code. The source code might be correct, and it’s just the other host, the client, or server. Or it could be the network. Maybe a router, firewall, or some other networking device is playing man-in-the-middle. For these types of issues, additional tools are essential. Below are a few tools and utilities that might help or at least provide some clues. Remove adsping 57 will check if a host is alive and connected to the network by sending an ICMP echo request. It communicates directly with the operating system’s TCP/IP protocol stack, so it works independently from any application running on the host.Below is an example of running ping on macOS: 9Note the statistics at the end of the output. This can be helpful when you’re trying to discover intermittent connectivity problems. For example, is there any packet loss? How much latency is there? You can check the round-trip times. If there’s a firewall between you and the other host, a ping’s echo request may not be allowed. Some firewall administrators implement policies that enforce this. The idea is that they don’t want their hosts to be discoverable. If this is the case and you have firewall rules added to allow the hosts to communicate, then make sure that the rules also allow ICMP to pass between them. ICMP is the protocol used by 57, but it’s also the protocol TCP and other lower-level protocols use to communicate error messages. If you’re experiencing strange behavior or slow connections, this could be the reason.ICMP messages are identified by type and code. To give you an idea of the important information they carry, here are a few: ICMP TypeICMP CodeDescription80Echo request00Echo reply30Destination network unreachable31Destination host unreachable32Destination protocol unreachable33Destination port unreachable34Fragmentation required, and DF flag set110TTL expired in transit See the article for information regarding fragmentation and ICMP messages. This is an example of something that can cause strange behavior. netstatIn the section , you learned how 37 can be used to display information about sockets and their current state. This utility is available on macOS, Linux, and Windows.That section didn’t mention the columns 60 and 61 in the example output. These columns will show you the number of bytes that are held in network buffers that are queued for transmission or receipt, but for some reason haven’t been read or written by the remote or local application.In other words, the bytes are waiting in network buffers in the operating system’s queues. One reason could be that the application is CPU bound or is otherwise unable to call 37 or 60 and process the bytes. Or there could be network issues affecting communications, like congestion or failing network hardware or cabling.To demonstrate this and see how much data you can send before seeing an error, you can try out a test client that connects to a test server and repeatedly calls 60. The test server never calls 37. It just accepts the connection. This causes the network buffers on the server to fill, which eventually raises an error on the client.First, start the server: 0Then run the client to see what the error is: 1Here’s 37 output from while the client and server are still running, with the client printing out the error message above multiple times: 2The first entry is the server ( 38 has port 65432): 3Notice the 60: 69.The second entry is the client ( 70 has port 65432): 4Notice the 61: 72.The client sure was trying to write bytes, but the server wasn’t reading them. This caused the server’s network buffer queue to fill on the receive side and the client’s network buffer queue to fill on the send side. WindowsIf you work with Windows, there’s a suite of utilities that you should definitely check out if you haven’t already: Windows Sysinternals. One of them is 73. TCPView is a graphical 37 for Windows. In addition to addresses, port numbers, and socket state, it’ll show you running totals for the number of packets and bytes sent and received. Like with the Unix utility 55, you also get the process name and ID. Check the menus for other display options.WiresharkSometimes you need to see what’s happening on the wire. Forget about what the application log says or what the value is that’s being returned from a library call. You want to see what’s actually being sent or received on the network. Just like with debuggers, when you need to see it, there’s no substitute. Wireshark is a network protocol analyzer and traffic capture application that runs on macOS, Linux, and Windows, among others. There’s a GUI version named 76 and also a terminal, text-based version named 77.Running a traffic capture is a great way to watch how an application behaves on the network and gather evidence about what it sends and receives, and how often and how much. You’ll also be able to see when a client or server closes or aborts a connection or stops responding. This information can be extremely helpful when you’re troubleshooting. There are many good tutorials and other resources on the web that will walk you through the basics of using Wireshark and TShark. Here’s an example of a traffic capture using Wireshark on the loopback interface: Here’s the same example shown above using 77: 5Next up, you’ll get more references to support your socket programming journey! ReferenceYou can use this section as a general reference with additional information and links to external resources. Python Documentation
ErrorsThe following is from Python’s 79 module documentation:
Here are some common errors you’ll probably encounter when working with sockets: Exception 81 ConstantDescriptionBlockingIOErrorEWOULDBLOCKResource temporarily unavailable. For example, in non-blocking mode, when calling 4 and the peer is busy and not reading, the send queue (network buffer) is full. Or there are issues with the network. Hopefully this is a temporary condition.OSErrorEADDRINUSEAddress already in use. Make sure that there’s not another process running that’s using the same port number and that your server is setting the socket option 83: 84.ConnectionResetErrorECONNRESETConnection reset by peer. The remote process crashed or did not close its socket properly, also known as an unclean shutdown. Or there’s a firewall or other device in the network path that’s missing rules or misbehaving.TimeoutErrorETIMEDOUTOperation timed out. No response from peer.ConnectionRefusedErrorECONNREFUSEDConnection refused. No application listening on specified port.Socket Address Families 6 and 86 represent the address and protocol families used for the first argument to 7. APIs that use an address expect it to be in a certain format, depending on whether the socket was created with 6 or 86.Address FamilyProtocolAddress TupleDescription 6IPv4 7 8 is a string with a hostname like 93 or an IPv4 address like 94. 01 is an integer. 86IPv6 18 8 is a string with a hostname like 93 or an IPv6 address like 00. 01 is an integer. 02 and 03 represent the 04 and 05 members in the C struct 06.Note the excerpt below from Python’s socket module documentation regarding the 8 value of the address tuple:
See Python’s for more information. This tutorial uses IPv4 sockets, but if your network supports it, try testing and using IPv6 if possible. One way to support this easily is by using the function . It translates the 8 and 01 arguments into a sequence of five-tuples that contains all of the necessary arguments for creating a socket connected to that service. 13 will understand and interpret passed-in IPv6 addresses and hostnames that resolve to IPv6 addresses, in addition to IPv4.The following example returns address information for a TCP connection to 14 on port 15:>>> 6Results may differ on your system if IPv6 isn’t enabled. The values returned above can be used by passing them to 7 and 17. There’s a client and server example in the of Python’s socket module documentation.Using HostnamesFor context, this section applies mostly to using hostnames with 9 and 2, or 3, when you intend to use the loopback interface, “localhost.” However, it also applies any time you’re using a hostname and there’s an expectation of it resolving to a certain address and having a special meaning to your application that affects its behavior or assumptions. This is in contrast to the typical scenario of a client using a hostname to connect to a server that’s resolved by DNS, like www.example.com.The following is from Python’s 79 module documentation:
The standard convention for the name “localhost” is for it to resolve to 00 or 69, the loopback interface. This will more than likely be the case for you on your system, but maybe not. It depends on how your system is configured for name resolution. As with all things IT, there are always exceptions, and there are no guarantees that using the name “localhost” will connect to the loopback interface.For example, on Linux, see 24, the Name Service Switch configuration file. Another place to check on macOS and Linux is the file 25. On Windows, see 26. The 27 file contains a static table of name-to-address mappings in a simple text format. DNS is another piece of the puzzle altogether.Interestingly enough, as of June 2018, there’s an RFC draft Let ‘localhost’ be localhost that discusses the conventions, assumptions, and security around using the name “localhost.” What’s important to understand is that when you use hostnames in your application, the returned addresses could literally be anything. Don’t make assumptions regarding a name if you have a security-sensitive application. Depending on your application and environment, this may or may not be a concern for you. Note: Security precautions and best practices still apply, even if your application isn’t explicitly security-sensitive. If your application accesses the network, it should be secured and maintained. This means, at a minimum:
Regardless of whether or not you’re using hostnames, if your application needs to support secure connections through encryption and authentication, then you’ll probably want to look into using TLS. This is its own separate topic and beyond the scope of this tutorial. See Python’s ssl module documentation to get started. This is the same protocol that your web browser uses to connect securely to web sites. With interfaces, IP addresses, and name resolution to consider, there are many variables. What should you do? Here are some recommendations that you can use if you don’t have a network application review process: ApplicationUsageRecommendationServerloopback interfaceUse an IP address, such as 00 or 69.Serverethernet interfaceUse an IP address, such as 07. To support more than one interface, use an empty string for all interfaces/addresses. See the security note above.Clientloopback interfaceUse an IP address, such as 00 or 69.Clientethernet interfaceUse an IP address for consistency and non-reliance on name resolution. For the typical case, use a hostname. See the security note above.For clients or servers, if you need to authenticate the host that you’re connecting to, look into using TLS. Blocking CallsA socket function or method that temporarily suspends your application is a blocking call. For example, 1, 2, 4, and 5 block, meaning they don’t return immediately. Blocking calls have to wait on system calls (I/O) to complete before they can return a value. So you, the caller, are blocked until they’re done or a timeout or other error occurs.Blocking socket calls can be set to non-blocking mode so they return immediately. If you do this, then you’ll need to at least refactor or redesign your application to handle the socket operation when it’s ready. Because the call returns immediately, data may not be ready. The callee is waiting on the network and hasn’t had time to complete its work. If this is the case, then the current status is the 81 value 38. Non-blocking mode is supported with .By default, sockets are always created in blocking mode. See for a description of the three modes. Closing ConnectionsAn interesting thing to note with TCP is that it’s completely legal for the client or server to close their side of the connection while the other side remains open. This is referred to as a “half-open” connection. It’s the application’s decision whether or not this is desirable. In general, it’s not. In this state, the side that has closed their end of the connection can no longer send data. They can only receive it. This approach isn’t necessarily recommended, but as an example, HTTP uses a header named “Connection” that’s used to standardize how applications should close or persist open connections. For details, see . When designing and writing your application and its application-layer protocol, it’s a good idea to go ahead and work out how you expect connections to be closed. Sometimes this is obvious and simple, or it’s something that can take some initial prototyping and testing. It depends on the application and how the message loop is processed with its expected data. Just make sure that sockets are always closed in a timely manner after they complete their work. Byte EndiannessSee Wikipedia’s article on endianness for details on how different CPUs store byte orderings in memory. When interpreting individual bytes, this isn’t a problem. However, when you’re handling multiple bytes that are read and processed as a single value, for example a 4-byte integer, the byte order needs to be reversed if you’re communicating with a machine that uses a different endianness. Byte order is also important for text strings that are represented as multi-byte sequences, like Unicode. Unless you’re always using true, strict ASCII and control the client and server implementations, you’re probably better off using Unicode with an encoding like UTF-8 or one that supports a byte order mark (BOM). It’s important to explicitly define the encoding used in your application-layer protocol. You can do this by mandating that all text is UTF-8 or using a “content-encoding” header that specifies the encoding. This prevents your application from having to detect the encoding, which you should avoid if possible. This becomes problematic when there is data involved that’s stored in files or a database and there’s no metadata available that specifies its encoding. When the data is transferred to another endpoint, it’ll have to try to detect the encoding. For a discussion, see Wikipedia’s Unicode article, which references :
The takeaway from this is to always store the encoding used for data that’s handled by your application if it can vary. In other words, try to somehow store the encoding as metadata if it’s not always UTF-8 or some other encoding with a BOM. Then you can send that encoding in a header along with the data to tell the receiver what it is. The byte ordering used in TCP/IP is and is referred to as network order. Network order is used to represent integers in lower layers of the protocol stack, like IP addresses and port numbers. Python’s socket module includes functions that convert integers to and from network and host byte order: FunctionDescription 39Convert 32-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. 40Convert 16-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. 41Convert 32-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. 42Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.You can also use the struct module to pack and unpack binary data using format strings: 7ConclusionYou covered a lot of ground in this tutorial! Networking and sockets are large subjects. If you’re new to networking or sockets, don’t be discouraged by all of the terms and acronyms. There are a lot of pieces to become familiar with in order to understand how everything works together. However, just like Python, it will start to make more sense as you get to know the individual pieces and spend more time with them. In this tutorial, you:
From here, you can use your custom class and build upon it to learn and help make creating your own socket applications easier and faster. To review the examples, you can click the link below: Get Source Code: Click here to get the source code you’ll use for the examples in this tutorial. Congratulations on making it to the end! You are now well on your way to using sockets in your own applications. Best of luck on your sockets development journey. Mark as Completed 🐍 Python Tricks 💌 Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team. Send Me Python Tricks » About Nathan Jennings Nathan is a member of the Real Python tutorial team who started his programmer career with C a long time ago, but eventually found Python. From web applications and data collection to networking and network security, he enjoys all things Pythonic. » More about NathanEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are: Aldren Brad Geir Arne Ian Jim Joanna Kate Master Real-World Python Skills With Unlimited Access to Real Python Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » Master Real-World Python Skills Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » What Do You Think? Rate this article: Tweet Share Share EmailWhat’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know. Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal. |