How to work with WebSockets in Python

1 min

Sockets are a low-level network communication method used to create, connect and manage network connections using the TCP/IP protocols. In Python, the socket module provides the necessary functions to work with sockets. Here is an example of how to create a simple socket in Python:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

The first line of the script imports the socket module. The second line creates a socket object, with the socket.AF_INET argument specifying that it is an IPv4 socket and the socket.SOCK_STREAM argument specifying that it uses the TCP protocol.

Once the socket is created, you can use the bind() method to associate the socket with a specific address and port, and then use the listen() method to listen for incoming connections. The accept() method is used to accept a connection, and the send() and recv() methods are used to send and receive data, respectively.

Here's an example of a basic server and client that communicate with each other using sockets in Python:

Server

import socket

# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a specific address and port
s.bind(("localhost", 12345))

# Listen for incoming connections
s.listen(5)

while True:
    # Accept a connection
    client, address = s.accept()
    print("Got a connection from", address)

    # Send a message to the client
    client.send(b"Thank you for connecting")

    # Close the connection
    client.close()

Client

import socket

# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server
s.connect(("localhost", 12345))

# Receive data from the server
print(s.recv(1024))

# Close the connection
s.close()

In this example, the server creates a socket object and binds it to the localhost address and port 12345. It then listens for incoming connections and, when one is received, sends a message to the client and closes the connection. On the client side, a socket object is created and used to connect to the server. The client then receives data from the server and closes the connection.

It's important to note that this is a very basic example, and in a real-world scenario, you may need to add error handling, encryption and other features for security and reliability.