EX.
NO 3: Demonstrate Applications using TCP sockets using python
i) Echo client and echo server
AIM:
To create a simple Echo Client and Echo Server using Python
PROGRAM:
Echo Server:
import socket
# Define server host and port
HOST = '127.0.0.1' # Localhost
PORT = 12345 # Port to bind to
# Create a TCP/IP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_socket.bind((HOST, PORT))
# Enable the server to accept connections (max 1 connection in the queue)
server_socket.listen(1)
print(f"Server listening on {HOST}:{PORT}")
# Wait for a connection
connection, client_address = server_socket.accept()
print(f"Connected by {client_address}")
try:
# Keep receiving and echoing messages from the client
while True:
data = connection.recv(1024) # Buffer size
if not data:
break # No more data received, exit the loop
print(f"Received: {data.decode()}")
# Echo the received message back to the client
connection.sendall(data)
finally:
# Clean up the connection
connection.close()
server_socket.close()
Echo Client:
import socket
# Define server host and port
HOST = '127.0.0.1' # Localhost
PORT = 12345 # Port to connect to
# Create a TCP/IP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
client_socket.connect((HOST, PORT))
# Send a message to the server
message = "Hello, Server!"
print(f"Sending message: {message}")
client_socket.sendall(message.encode())
# Receive the echoed message from the server
data = client_socket.recv(1024) # Buffer size
print(f"Received from server: {data.decode()}")
# Close the socket
client_socket.close()
Server Output:
Server listening on 127.0.0.1:12345
Connected by ('127.0.0.1', 56789)
Received: Hello, Server!
Client Output:
Sending message: Hello, Server!
Received from server: Hello, Server!
RESULT:
Echo client and echo server program is successfully completed.
3)ii) Chat
AIM:
To create a simple chat application using TCP sockets in Python,
Chat Server (TCP Server)
The server will:
Listen for incoming connections from clients.
Accept messages from clients and broadcast them to all connected clients.
Chat Client (TCP Client)
The client will:
Connect to the server.
Send messages to the server.
Display received messages from other clients.
Chat Server Code:
import socket
import threading
# List to keep track of client connections
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:
client.close()
clients.remove(client)
# Handle communication with each client
def handle_client(client_socket):
# Welcome message
client_socket.send("Welcome to the chat! Type 'exit' to leave.\n".encode())
while True:
try:
message = client_socket.recv(1024)
if message:
print(f"Received: {message.decode('utf-8')}")
broadcast(message, client_socket)
else:
break
except:
break
# Remove client from the list and close connection
clients.remove(client_socket)
client_socket.close()
# Start the chat server
def chat_server(host, port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
print(f"Server started on {host}:{port}")
while True:
client_socket, client_address = server_socket.accept()
print(f"New connection from {client_address}")
clients.append(client_socket)
# Start a new thread for each client
thread = threading.Thread(target=handle_client, args=(client_socket,))
thread.start()
if __name__ == "__main__":
chat_server("127.0.0.1", 65432) # Server running on localhost:65432
Chat Client Code:
import socket
import threading
# Function to receive messages from the server
def receive_messages(client_socket):
while True:
try:
message = client_socket.recv(1024)
if message:
print(message.decode('utf-8'))
else:
break
except:
break
# Function to send messages to the server
def send_messages(client_socket):
while True:
message = input()
if message.lower() == 'exit':
client_socket.send("User has left the chat.\n".encode())
break
client_socket.send(message.encode())
# Start the chat client
def chat_client(host, port):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
# Start receiving messages from the server
thread = threading.Thread(target=receive_messages, args=(client_socket,))
thread.start()
# Send messages to the server
send_messages(client_socket)
client_socket.close()
if __name__ == "__main__":
chat_client("127.0.0.1", 65432) # Connect to the server running on localhost:65432
Server Output:
Server started on 127.0.0.1:65432
New connection from ('127.0.0.1', 12345)
New connection from ('127.0.0.1', 12346)
Client 1 Output (After Connecting to Server):
Welcome to the chat! Type 'exit' to leave.
Hello everyone!
Client 2 Output (After Connecting to Server):
Welcome to the chat! Type 'exit' to leave.
Hi, how are you?
RESULT:
Simple chat application using TCP sockets in Python program is completed successfully.
3)iii) File Transfer
AIM:
To implement file transfer using TCP sockets in Python,
Steps for File Transfer:
1. Server Side:
o The server listens on a specific port for incoming connections.
o It accepts the connection, receives the file data in chunks, and writes the data
to a file.
2. Client Side:
o The client connects to the server.
o It reads the file in binary mode and sends the data to the server in chunks
Server Code (File Transfer Server):
import socket
def file_server(host, port):
# Create a TCP/IP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the address and port
server_socket.bind((host, port))
# Enable the server to accept connections
server_socket.listen(1)
print(f"Server listening on {host}:{port}")
while True:
# Accept a client connection
client_socket, client_address = server_socket.accept()
print(f"Connection from {client_address} established.")
# Receive the file name
file_name = client_socket.recv(1024).decode()
print(f"Receiving file: {file_name}")
with open(f"received_{file_name}", "wb") as file:
while True:
# Receive the file data in chunks
data = client_socket.recv(4096)
if not data:
break
file.write(data)
print(f"File '{file_name}' received successfully.")
# Close the connection
client_socket.close()
if __name__ == "__main__":
file_server("127.0.0.1", 65432) # You can use a different port
Client Code (File Transfer Client):
import socket
def file_client(host, port, file_path):
# Create a TCP/IP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
client_socket.connect((host, port))
# Send the file name
file_name = file_path.split("/")[-1]
client_socket.send(file_name.encode())
# Open the file and send its content in chunks
with open(file_path, "rb") as file:
while True:
data = file.read(4096)
if not data:
break
client_socket.send(data)
print(f"File '{file_name}' sent successfully.")
# Close the connection
client_socket.close()
if __name__ == "__main__":
file_client("127.0.0.1", 65432, "sample_file.txt") # Path to the file you want to send
Server Output:
Server listening on 127.0.0.1:65432
Connection from ('127.0.0.1', 12345) established.
Receiving file: sample_file.txt
File 'sample_file.txt' received successfully.
Client Output:
File 'sample_file.txt' sent successfully.
RESULT:
File transfer using TCP sockets in Python program is completed successfully.