Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Computer Networks Lab

CSC-611

ASSIGNMENT- 3

NAME: ARYAN SONI


REGISTRATION NUMBER: 778
ROLL NUMBER: ECE/21118
PROBLEM STATEMENT:

1. Write a TCP socket program (in


C/C++/Java/Python) to establish connection between
client and server. The client program will send a
message to the server and the server program will
display the message.

Client program:
Server program:
Client code :
import socket
port=50000
portClient=8000
host="127.0.0.1"
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.bind((host, portClient))
client.connect((host, port))
while True:
data = input("Enter your message: ")
client.send(data.encode())
if
data=='quit':
break
print("Connection closed from server")
client.close()

Server code :
import socket

port=50000
host="127.0.0.1"

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


server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
1)
server.bind((host, port))
print("socket binded to %s" %(port))
server.listen(2)
print("Socket is listening...")

# Accepting/Establishing connection from client. conn,


addr = server.accept()
print('Got connection from', addr)

while True:
recieved_data = conn.recv(2048)
print("Message from client: ",recieved_data.decode())
if recieved_data.decode()=='quit':
break

print("Connection closed from client")

#Close the connection with the client


conn.close()
2.Write a TCP socket program where client sends a message
(string) to server; server echo back the characters at even
position if length of the string is even otherwise echo back the
characters at odd position. This process continues until the
client sends ‘bye;

Client code:
import socket
client_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 12345))
while True:
message = input("Enter message: ")
client_socket.send(message.encode())
if message.lower() == 'bye':
break
response = client_socket.recv(1024).decode()
print(f"Server response: {response}")
client_socket.close()

Server code :
import socket

def echo_even_odd(message):
length = len(message)
if length % 2 == 0:
return ''.join(message[i] for i in range(1, length, 2))
else:
return ''.join(message[i] for i in range(0, length, 2))
server_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', 12345))
server_socket.listen(5)

print("Server listening on port 12345")

while True:
client_socket, address = server_socket.accept()
print(f"Connection from {address}")

while True:
data = client_socket.recv(1024).decode()
print(f"Received message: {data}")

if data.lower() == 'bye':
break

response = echo_even_odd(data)
client_socket.send(response.encode())

client_socket.close()
OUTPUT:

You might also like