Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please answer this long question for me in python I am attaching all the pictures and given code below. Server code: ''' This module defines

Please answer this long question for me in python

I am attaching all the pictures and given code below.

image text in transcribed

image text in transcribed

image text in transcribed

image text in transcribed

image text in transcribed

image text in transcribed

image text in transcribed

image text in transcribed

Server code:

'''

This module defines the behaviour of server in your Chat Application

'''

import sys

import getopt

import socket

import util

class Server:

'''

This is the main Server Class. You will to write Server code inside this class.

'''

def __init__(self, dest, port):

self.server_addr = dest

self.server_port = port

self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

self.sock.settimeout(None)

self.sock.bind((self.server_addr, self.server_port))

def start(self):

'''

Main loop.

continue receiving messages from Clients and processing it

'''

raise NotImplementedError

# Do not change this part of code

if __name__ == "__main__":

def helper():

'''

This function is just for the sake of our module completion

'''

print("Server")

print("-p PORT | --port=PORT The server port, defaults to 15000")

print("-a ADDRESS | --address=ADDRESS The server ip or hostname, defaults to localhost")

print("-h | --help Print this help")

try:

OPTS, ARGS = getopt.getopt(sys.argv[1:],

"p:a", ["port=", "address="])

except getopt.GetoptError:

helper()

exit()

PORT = 15000

DEST = "localhost"

for o, a in OPTS:

if o in ("-p", "--port="):

PORT = int(a)

elif o in ("-a", "--address="):

DEST = a

SERVER = Server(DEST, PORT)

try:

SERVER.start()

except (KeyboardInterrupt, SystemExit):

exit()

CLIENT CODE:

'''

This module defines the behaviour of a client in your Chat Application

'''

import sys

import getopt

import socket

import random

from threading import Thread

import os

import util

'''

Write your code inside this class.

In the start() function, you will read user-input and act accordingly.

receive_handler() function is running another thread and you have to listen

for incoming messages in this function.

'''

class Client:

'''

This is the main Client Class.

'''

def __init__(self, username, dest, port):

self.server_addr = dest

self.server_port = port

self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.sock.settimeout(None)

self.name = username

def start(self):

'''

Main Loop is here

Start by sending the server a JOIN message.

Waits for userinput and then process it

'''

raise NotImplementedError

def receive_handler(self):

'''

Waits for a message from server and process it accordingly

'''

raise NotImplementedError

# Do not change this part of code

if __name__ == "__main__":

def helper():

'''

This function is just for the sake of our Client module completion

'''

print("Client")

print("-u username | --user=username The username of Client")

print("-p PORT | --port=PORT The server port, defaults to 15000")

print("-a ADDRESS | --address=ADDRESS The server ip or hostname, defaults to localhost")

print("-h | --help Print this help")

try:

OPTS, ARGS = getopt.getopt(sys.argv[1:],

"u:p:a", ["user=", "port=", "address="])

except getopt.error:

helper()

exit(1)

PORT = 15000

DEST = "localhost"

USER_NAME = None

for o, a in OPTS:

if o in ("-u", "--user="):

USER_NAME = a

elif o in ("-p", "--port="):

PORT = int(a)

elif o in ("-a", "--address="):

DEST = a

if USER_NAME is None:

print("Missing Username.")

helper()

exit(1)

S = Client(USER_NAME, DEST, PORT)

try:

# Start receiving Messages

T = Thread(target=S.receive_handler)

T.daemon = True

T.start()

# Start Client

S.start()

except (KeyboardInterrupt, SystemExit):

sys.exit()

UTIL CODE:

'''

This file contains basic utility function that you can use.

'''

MAX_NUM_CLIENTS = 10

def make_message(msg_type, msg_format, message=None):

'''

This function can be used to format your message according

to any one of the formats described in the documentation.

msg_type defines type like join, disconnect etc.

msg_format is either 1,2,3 or 4

msg is remaining.

'''

if msg_format == 2:

return "%s" % (msg_type)

if msg_format in [1, 3, 4]:

return "%s %s" % (msg_type, message)

return ""

Please code this in python as soon as possible

Simple Chat Application The main goal of this assignment is to introduce you to socket programming in the context of client-server application architectures. We begin by describing the role of the application server (1.1), application client (1.2), then provide a short introduction to socket programming (1.3), and finally, describe in detail the protocol (1.4) to be used for exchanging messages between the client and server. 1.1) Application-Server The application server is a multi-threaded server. It listens for new connections from clients at a given host and port, accepts them, and handles the messages sent from each client. The server can concurrently connect up to MAX_NUM_CLIENTS clients. This means that if MAX_NUM_CLIENTS is 10, at max only 10 clients can use the service at a time, and for a 11th client to connect, one of the previous 10 clients will need to be disconnected. When a client requests to join a server that already has MAX_NUM_CLIENTS, its request will be rejected. Furthermore, the server does not store information of disconnected clients. The server must handle all possible errors and remain alive until explicitly terminated. 1.2) Application-Client The application client represents the interface for your chat application, that connects to the application server with a unique username i.e. no two clients connected to the server at the same time can have the same username. It does the following tasks: a. Read user input from the standard input stream and send messages to the server, accordingly. b. Receive and handle messages from the server c. End the connection with the server and shutdown on receiving an error from the server. More information on this is given in Section 1.4. Before shutting down, it also shows a message to the user on why the connection is being terminated. For the application client and application server to communicate with each other over the Internet, we will use socket programming. Below we describe it. 1.3) Socket Programming Sockets allow applications to send and receive messages across a network. Sockets are an Operating System mechanism that connects processes to the networking stack. A port number identifies a socket. If an application has to send a message, it writes to a specific socket. If an application is expecting to receive messages, it listens on a socket for incoming messages. To create a socket, you need to: a. specify the transport protocol you will use, b. the address of the machine (referred to as IP address), and c. the port number you will use to identify the socket. In this assignment, your client should connect with the server using the transport protocol, TCP. TCP is a reliable transport protocol that sends a message from the sender to the receiver by first establishing an explicit connection. Furthermore, you will use the localhost as your IP address as you will be running the server and client on the same machine. The port number must be different for each entity as one port can only be used by one process. The server should listen on a fixed port number which all the clients need to know 1.4) Application API and Protocols Before describing the Application API and protocols in detail, we begin by listing down the sequence of events you should follow for establishing communication between clients. - First, establish a TCP connection with an already running server and send a "join" message from the client to the server. - The server should add the new client to its list of clients and store its TCP connection details so that it can send messages back to the client. - Any client can then send messages to any other client(s) connected to the server, using the protocol described in the next sections. The way users structure their input messages is important for the working of the application - the application will only understand commands sent in a certain format. These formats are explained in the following sections. A typical interactions flow between the server and a connected client then can be summarized as follows: a. User inputs a specific command string in the predefined formats into the Application Client input. This is a simple standard input (stdin). b. The client evaluates the input based on predefined formats, reformats it according to formats required for processing at the server (if needed), and sends the formatted message to the server. c. On receiving a message from a client, the server processes it, again based on predefined formats. d. Based on what command was processed, the server forwards a formatted message back to the client (for example, if a list of connected clients was requested) or forwards a message from the client to other clients (i.e. a text message or a file). In case of errors, appropriate error messages are sent back. e. A client receiving a server message decodes it according to the predefined formats and then outputs it to the Application Client in the formats specified. As an example, consider the following: - clients with usernames, client_1, client_2 and client_3 are connected to the server. Client client_3 inputs the following string: msg 2 client_1 client_2 Hello my friends! - The client application should interpret this as a message being sent to ' 2 ' other clients, namely client_1 and client_2. And the message text is 'Hello my friends!' - The client should then compile a message to send to the server. - The server must receive the message, understand that it is incoming from client_3 3 and the 2 intended recipients are client_l and client_2. - The recipients, client_1, and client_2, should then receive a message from the server and display it on msg: client_3: Hello my friends! This describes the basic crux of the chat application; your implementation will build up on this to include the required functionality and exception handling. This will require implementing application APIs and protocols. Application API are the actions that a user at a client can perform using the application i.e. the functionality that an application supports. For your app, this includes client joining and quitting, sending and receiving messages and files, getting a list of connected users, and a basic help function. For implementation purposes, each of these APIs (other than join which is automatically called on starting a client) are called on by the user at a client using string inputs of specific formats so the application client understands commands. Application protocols define how an application client and application server communicate with each other. As with user inputs, these need to follow specific conventions and formats so the client and server can understand messages sent and received and do appropriate processing. For this assignment, these constitute a set of protocols defined by message types (e.g. send_message, forward_file), which also include error messages for exception handling, and 4 fixed message string formats. The message exchanged for each protocol belongs to one of the 4 string formats. Since the messages are sent/received as strings, the different fields in a message will be separated by a single space character (""). The types are: Tuma: 2 List of usernames in Type 3 and 4 will be formatted as: Below we describe in detail the Application API and the protocols you will need to implement. 1.4a) Application API Each Application Client should be able to perform the tasks given below. For each function, the client must get the user input from standard input (stdin) and process the input according to the below-mentioned formats. If the input does not match with any format, the client should print on stdout: incorrect user input format Your chat application should support the following API: 1) Message: Function: Sends a message from this client to other clients connected to the server using the names specified in the user input. The application server must ensure that the client (whom the message is sent to) will only receive the message once even if his/her username appears more than once in the user input. User input: msg > username 2> message> 2) Available Users: Function: Lists all the usernames of clients connected to the application-server (including itself). All names must be in one line in ascendingly sorted order. User input: list 3) File-Sharing: Function: Sends a file to other clients connected to the server. The other clients should save the file with the same filename (as specified by the sender, includes the file extension i.e. .txt or .py) prefixed with their username (e.g. client1_solution.py). User input: file > 4) Help: Function: Prints all the possible user inputs and their format User input: help 5) Quit: Function: Let the application server know that the client is disconnecting, close the TCP connection with the application server, print the following message to stdout, and shutdown gracefully. quitting User input: quit 1.4b) Protocols A message is a basic unit of data transfer between client and server. The different types of messages that can be exchanged between a client and a server are as follows (the message formats mentioned are given below): 1) join Client to the server Message Format: Type 1 Sender Action: This message serves as a request to join the chat application. Whenever a new client comes, it will send this message to the server. Receiver Action: When a server receives this message, 3 things can happen at the server: 1) The server has already MAX_NUM_CLIENTS, so it will reply with err_server_full message and will print disconnected: server full 2) The username is already taken by another client. In this case, the server will reply with an err_username_unavailable message and will print: disconnected: username not available 3) The server allows the user to join the chat. In this case, it will not reply but will print: join: 2) request_users_list Client to server Message Format: Type 2 Sender Action: A client sends this message to the server when it reads a list as user input. Receiver Action: The server will reply with RESPONSE_USERS_LIST message and will print: request_users_list: 3) response_users_list Server to client Message Format: Type 3 Sender Action: The server will send the list of all usernames (including the one that has requested this list) to the client. Receiver Action: Upon receiving this message, the client will print: list: > ... where the usernames are ascendingly sorted. 4) send_message Client to server Message Format: Type 4 Sender Action: A client sends this message to the server. Receiver Action: The server forwards this message to each user whose name is specified in the request. It will also print: msg: For each username that does not correspond to any client, the server will print: msg: to non-existent user 5) forward_message Server to client Message Format: Type 4 Sender Action: The server will forward the messages it receives from clients. It will specify the username of the sender in the message in the List of Usernames field. Receiver Action: The client, upon receiving this message, will print: msg: > 6) send_file Client to server Message Format: Type 4 Sender Action: A client sends this message to the server. In the place of the message, it will place the file (the filename will be placed before the actual file content, separated by space). Receiver Action: The server forwards this file to each user whose name is specified in the request. It will also print: file: For each username that does not correspond to any client, the server will print: file: to non-existent user 7) forward_file Server to client Message Format: Type 4 Sender Action: The server will forward the files it receives from clients. It will specify the username of the sender in the message in the List of Usernames field. Receiver Action: The client, upon receiving this message, will save the file and print: file: : 8) disconnect Client to server Message Format: Type 1 Sender Action: The client will send this to the server to let it know it's disconnecting Receiver Action: The server upon receiving this, shuts down the connection and removes this user from its list of online users. The server will also print: disconnected: 9) err_unknown_message Server to client Message Format: Type 2 Sender Action: The server will send this message to a client if it receives a message, it does not recognize, from that client. The server will also print: disconnected: sent unknown command Receiver Action: The client, upon receiving this message, closes the connection to the server and shuts down with the following message on screen: disconnected: server received an unknown command 10) err_server_full Server to client Message Format: Type 2 Sender Action: The server will send this message. Receiver Action: The client, upon receiving this message, closes the connection to the server and shuts down with the following message on screen: disconnected: server full 11) err_username_unavailable Server to client Message Format: Type 2 Sender Action: The server will send this message. Receiver Action: The client, upon receiving this message, closes the connection to the server and shuts down with the following message on screen: disconnected: username not available

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions