In this Python Socket Programming article we want to learn about Socket Programming in Python with select(), so Python is popular language for developing network applications, and socket programming is an important part of network programming in Python. Socket programming allows you to communicate between two or more computers over a network. in this article we want to learn about socket programming in Python using the select() method, which allows us to monitor multiple sockets at the same time.
What is select() in Python ?
select() method is builtin function in Python socket module that allows you to monitor multiple sockets at the same time. when you use select(), you can wait for input or output on one or more sockets without blocking the program. this means that you can monitor multiple sockets simultaneously and only perform operations on those sockets when they are ready for input or output.
Using select() for socket programming in Python
Let’s take a look at an example of how to use select() in Python for socket programming. we want to create simple server that listens for incoming connections on a socket and uses select() to monitor multiple sockets.
First we need to import our required libraries
1 2 |
import socket import select |
After that we want to define some variables to hold our server address and port
1 2 |
HOST = 'localhost' PORT = 1234 |
Now, let’s create a socket and bind it to our address and port
1 2 3 4 |
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((HOST, PORT)) server_socket.listen() |
We have set some options on the socket to allow us to reuse the address and port, and then we have started listening for incoming connections.
After that we want to create a list to hold our sockets and add our server socket to it
1 |
sockets_list = [server_socket] |
Now, we will enter an infinite loop to listen for incoming connections and monitor our sockets using select():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
while True: # Use select() to monitor our sockets for input or output read_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list) # Loop through sockets that are ready for input for sock in read_sockets: # Handle new connections if sock == server_socket: client_socket, client_address = server_socket.accept() sockets_list.append(client_socket) print('New connection from {}'.format(client_address)) # Handle incoming data else: data = sock.recv(1024) if data: # Broadcast message to all connected clients message = '{}: {}'.format(sock.getpeername(), data.decode()) print(message) for client_socket in sockets_list: if client_socket != server_socket and client_socket != sock: client_socket.send(message.encode()) # Remov disconnected clients else: sockets_list.remove(sock) print('Client disconnected') sock.close() |
In the above code we have used select() to monitor our sockets for input or output. we pass our list of sockets to monitor, an empty list for sockets to write to and the same list of sockets to monitor for exceptions. this means that select() will return a list of sockets that are ready for input, list of sockets that are ready for output (which is empty in this case) and a list of sockets that have exceptions.
After that we loop through the sockets that are ready for input and handle new connections or incoming data. if a client sends data, we broadcast the message to all connected clients. if a client disconnects, we remove the socket from our list of sockets and close the connection.
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import socket import select # Define the host and port to listen on HOST = 'localhost' PORT = 1234 # Create a socket and bind it to the host and port server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((HOST, PORT)) server_socket.listen() # Add server socket to list of sockets to monitor sockets_list = [server_socket] print('Server started on {}:{}'.format(HOST, PORT)) while True: # Use select() to monitor our sockets for input or output read_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list) # Loop through sockets that are ready for input for sock in read_sockets: # Handle new connections if sock == server_socket: client_socket, client_address = server_socket.accept() sockets_list.append(client_socket) print('New connection from {}'.format(client_address)) # Handle incoming data else: data = sock.recv(1024) if data: # Broadcast the message to all connected clients message = '{}: {}'.format(sock.getpeername(), data.decode()) print(message) for client_socket in sockets_list: if client_socket != server_socket and client_socket != sock: client_socket.send(message.encode()) # Remove disconnected clients else: sockets_list.remove(sock) print('Client disconnected') sock.close() |
Save the file in server.py file, and after that run that your code via terminal like this (python server.py), this will start the server and it will begin listening for incoming connections on the specified host and port. after that you use a client program (such as telnet or netcat) to connect to the server and communicate with it over the network.
This is our server in terminal
also you can use telnet to connect like this telnet localhost 1234
Learn More
- Python Socket Programming Examples
- Python Socket Programming for Beginners
- Python Socket Server Tutorial
- Python Socket Client Example
- TCP Socket Programming in Python