Eyuel Tesfaye 0014 (Socket Programming)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Department of Electrical and Computer Engineering

Institute of Technology (IOT)

Individual assignment - Python Socket Programming

NAME ID

Eyuel Tesfaye MEECER/ 0014/11

Submitted To: Mr .Bahailu


Python Socket Programming

1. Introduction
Socket programming in Python is a powerful way to establish network connections and enable
communication between different nodes. Socket programming is essential for building network
applications, enabling communication between computers over a network. Python's socket library
provides a convenient and flexible way to work with sockets for various network-related tasks.

2. Socket Basics

2.1 Creating a Socket

The first step in socket programming is creating a socket object. The socket() function is used for
this purpose, specifying the address family and socket type. For example, to create a TCP socket
for IPv4:

import socket

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

2.2 Binding and Addressing

Once you have a socket object, it needs to be bound to an address and port using the bind()
method. This associates the socket with a specific network interface and port number.

s.bind(('127.0.0.1', 8000))

3. Server Socket

3.1 Listening for Connections


In server socket programming, you need to listen for incoming connections using the listen()
method. This specifies the maximum number of queued connections that can be handled.

s.listen(5)

3.2 Accepting Connections

When a client attempts to connect, you can accept the incoming connection using the accept()
method. This returns a new socket object representing the connection and the client's address.

conn, addr = s.accept()

4. Client Socket

4.1 Connecting to a Server

For client socket programming, you need to establish a connection to a server using the connect()
method, specifying the server's address and port.

s.connect(('127.0.0.1', 8000))

4.2 Sending and Receiving Data

Once connected, you can use the socket to send and receive data. The send() method is used to
send data, and recv() is used to receive data.

 # Sending data

s.send(b'Hello, world!')

 Receiving data

data = s.recv(1024)

5. Error Handling

Effective error handling is crucial in socket programming. Be prepared to handle exceptions like
socket.error, socket.timeout, and ConnectionRefusedError. Robust error handling ensures your
application gracefully handles unexpected issues.
6. Concurrency

To handle multiple connections simultaneously, consider using concurrency techniques like multi-
threading or asynchronous programming with libraries such as asyncio. Concurrency is crucial for
building scalable network applications.

7. Socket Options

Socket options allow you to configure various aspects of socket behavior. You can customize
settings such as socket timeout and socket reuse using methods like settimeout() and setsockopt().

8. Debugging Tools

Debugging tools and techniques are essential for troubleshooting socket-related issues. Tools like
Wireshark can help analyze network traffic, and standard debugging practices can aid in
diagnosing and resolving communication problems.

9. Sample Code

Here’s a sample code that simulates a basic chat application. The server will broadcast messages
from one client to all connected clients.

Server Code (broadcast chat messages):

import socket

import threading

# Server configuration

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

server.bind(('127.0.0.1', 8080))
server.listen(5)

# List to store connected clients

clients = []

# Broadcast function to send messages to all clients

def broadcast(message, client_socket):

for client in clients:

if client != client_socket:

try:

client.send(message)

except:

# Remove disconnected clients

clients.remove(client)

# Handle client connections

def handle_client(client_socket):

while True:

try:

message = client_socket.recv(1024)

if message:

print(f"Received: {message.decode()}")

broadcast(message, client_socket)

except:

# Remove disconnected clients

clients.remove(client_socket)
client_socket.close()

break

# Accept and handle client connections

while True:

client_socket, client_address = server.accept()

print(f"Connected to {client_address}")

clients.append(client_socket)

client_handler = threading.Thread(target=handle_client, args=(client_socket,))

client_handler.start()

Client Code (chat client):

import socket

import threading

# Client configuration

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

client.connect(('127.0.0.1', 8080)

# Receive and display messages

def receive_messages():

while True:

try:
message = client.recv(1024)

if message:

print(message.decode())

except:

client.close()

break

# Send messages

def send_messages():

while True:

message = input()

client.send(message.encode())

# Create threads for receiving and sending messages

receive_thread = threading.Thread(target=receive_messages)

send_thread = threading.Thread(target=send_messages)

receive_thread.start()

send_thread.start()

The output of the chat application might look like:

Server: Connected to ('127.0.0.1', 56789)

Client 1: Connected to server.

Client 2: Connected to server.


(Client 1 enters "")

Server: Received: Hello

Client 2: Hello

(Client 2 enters "Hi")

Server: Received: Hi

Client 1: Hi

Server Output
Client 1

Client 2
10. Closing Sockets

When you're finished with a socket, it's essential to close it using the close() method. This releases
associated resources and ensures proper cleanup.

11. References

1. Python Socket Library Documentation


2. Python Official Website
3. Beej's Guide to Network Programming
4. Wireshark - Network Protocol Analyzer

In conclusion, socket programming in Python is a versatile and powerful tool for various network
communication needs. Whether you're developing network services, real-time chat applications,
or efficient data transfer services, Python's socket library offers a robust foundation for building
network applications. Python's simplicity and flexibility make it a popular choice for networking,
and with the right approach, you can create efficient and reliable solutions for a wide range of
network-related tasks.

You might also like