How to Work with Sockets in Python

09/11/2021

Contents

In this article, you will learn how to work with sockets in Python.

Using the socket module

Socket communication is a way to establish communication between two different programs running on different devices over a network. In Python, you can work with sockets using the socket module.

Here is a simple example of how to use socket communication in Python:

Import the socket module:
import socket
Create a socket object:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Here, AF_INET refers to the address family (in this case, IPv4), and SOCK_STREAM refers to the socket type (in this case, a TCP socket).

Bind the socket to a specific address and port:
s.bind(('localhost', 8000))

Here, localhost is the hostname or IP address of the machine on which the server is running, and 8000 is the port number.

Listen for incoming connections:
s.listen(1)

This will allow the server to listen for incoming connections. The argument 1 specifies the maximum number of queued connections.

Accept incoming connections:
conn, addr = s.accept()

This will accept an incoming connection and return a new socket object representing the connection, as well as the address of the client.

Send and receive data:
data = conn.recv(1024)
conn.send(b'Hello, client!')

This will receive data from the client (up to 1024 bytes), and send a response back.

Close the connection:
conn.close()

This will close the connection with the client.

Here is an example of a complete server implementation:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 8000))
s.listen(1)

conn, addr = s.accept()
print('Connection from', addr)

data = conn.recv(1024)
print('Received:', data.decode())

conn.send(b'Hello, client!')

conn.close()

And here is an example of a client implementation:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 8000))

s.send(b'Hello, server!')
data = s.recv(1024)
print('Received:', data.decode())

s.close()