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

DIGITAL ASSIGNMENT 4

BCSE308P
COMPUTER NETWORKS

Name: Harshil Nanda


Reg No: 21BCE0918
Q1. Create a client server application using UDP
socket.

Code:

Server:
import socket

# Create a UDP socket


sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Bind the socket to a specific IP address and port


server_address = ('localhost', 12345)
sock.bind(server_address)

print('Server listening on {}:{}'.format(*server_address))

while True:
print('\nWaiting for a message...')
data, address = sock.recvfrom(4096)

print('Received message: "{}" from {}'.format(data.decode(), address))


# Process the received message
response = 'Hello, client!'

# Send the response back to the client


sock.sendto(response.encode(), address)

Client:
import socket

# Create a UDP socket


sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Server address
server_address = ('localhost', 12345)

# Send a message to the server


message = 'Hello, server!'
sock.sendto(message.encode(), server_address)

# Receive the response from the server


data, address = sock.recvfrom(4096)

print('Received response: "{}" from {}'.format(data.decode(), address))


Output:

You might also like