Categories

Beginners Guide to Python Socket Programming

The socket module in Python provides a way to communicate between two computers using the TCP/IP protocol. Here we will write a simple chat application that consists of a server and a client.

What is a Socket?

A socket is one endpoint of a two-way communication link between two programs running on the network. Sockets are used to create a connection between a client program and a server program. The client program is run on one machine and sends a request to a certain IP address and port number; the server program is run on the other machine and waits for requests on that specified port.

Python Socket Programming Steps

Step 1: Import Socket Module

The first step in Python socket programming is to import the socket module.

import socket

Step 2: Create a Socket

Next, you need to create a socket. You can do this using the socket.socket() method.

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

Here, socket.AF_INET refers to the address family ipv4 and socket.SOCK_STREAM means that it is a TCP socket.

Step 3: Bind the Socket

The next step is to bind the socket to a specific address and port. You can do this using the socket.bind() method.

s.bind((host, port))

Step 4: Listen for Connections

Once you have bound your socket, you can start listening for connections. You can do this using the socket.listen() method.

s.listen()

Step 5: Accept Connections

After listening for connections, you can accept them using the socket.accept() method. This method will return a new socket object and the address of the client.

client_socket, addr = s.accept()

Step 6: Send and Receive Data

Once you have a connection, you can send and receive data using the send() and recv() methods.

data = client_socket.recv(1024)
client_socket.send(data)

Step 7: Close the Socket

When you are done with the connection, you should close the socket to free up resources.

s.close()

Simple Chat Server & Client Example

Server Code:

import socket

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

# Define the host and the port
host = 'localhost'
port = 12345

# Bind the socket
s.bind((host, port))

# Start listening for connections
s.listen()

print(f'Server started on {host}:{port}, waiting for connections...')

while True:
    # Accept a connection
    client_socket, addr = s.accept()

    print(f'Got a connection from {addr}')

    # Receive data
    data = client_socket.recv(1024).decode('utf-8')
    print(f'Received message: {data} from: {addr}')

    # Send data
    response = 'Server response: ' + data
    client_socket.send(response.encode('utf-8'))

    # Close the connection
    client_socket.close()

Client Code:

import socket

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

# Define the host and the port
host = 'localhost'
port = 12345

# Connect to the server
s.connect((host, port))

# Send some data
message = 'Hello, Server!'
s.send(message.encode('utf-8'))

# Receive data
data = s.recv(1024).decode('utf-8')
print(f'Received from server: {data}')

# Close the connection
s.close()

Note: Remember to run the server script first before running the client script. Also, this simple chat application sends and receives a single message; to have a continuous chat, you can wrap the sending and receiving of data in a loop. But remember to set a condition to break the loop to prevent an infinite loop.

Leave a Reply

Your email address will not be published. Required fields are marked *