Question

In: Computer Science

In this part, you will implement a Server class that will accept only one connection, process...

In this part, you will implement a Server class that will accept only one connection, process its requests, and then the Server will end.

Create a Server class in the package edu.ucdenver.server
The constructor should take the port and backlog to open the server.
The server should implement the Runnable interface.
Override the following public methods:
public void run()
This will implement your server. Similar to runServer() from our lecture examples.
Upon a client connection, the server will listen for requests. Once one is received, will be processed (see below) and the response will be send to the server.
Keep accepting requests until the client disconnect. No termination message will be send, the client will just disconnect.
Protocol:
the communication will be text based.
fields will be delimited by a vertical bar ( | )
clients may send either two requests:
"E|text" -> requesting the server to encode the clean text "text" into Morse Code
"D|morse" -> requesting the server to decode the received text "morse" from Morse Code to clean text
Server may respond:
"0|text" -> to either E and D requests. Text will correspond with either the encoded or decoded string.
"1|Not Implemented" -> if the server got a requests unrecognized by the server. E.g. "C|" or "E Hello world"
"2|Invalid Message Format" -> if the message format is not correct. Eg. "E", the command is correct but the arguments received are not (in this case no text was sent).
Important Notes:
Quotes were added just to delimit the message descriptions, and are not part of the actual message.
Make sure to use the Class defined in Part #1
To test your server, use the text-based client class implemented in our hands-on examples. We will be using a variation of that to test your server.
Make sure your server terminates after the client disconnects. Your code test will be aborted otherwise.

Solutions

Expert Solution

#import socket module
__author__ = 'Xi Su'

from socket import *
import datetime

"""
memo:
"**".join() :for loop join string and concatenate by **
date format use date.date.now.strftime()

"""
serverSocket = socket(AF_INET, SOCK_STREAM) #Prepare a sever socket
#Fill in start

serverPort = 6789
serverSocket.bind(('',serverPort))
serverSocket.listen(5)

#Fill in end
while True:
   #Establish the connection
   print 'Ready to serve...'
   connectionSocket, addr = serverSocket.accept()
   print "addr:\n", addr
   #Fill in start
   #Fill in end
   try:
       message = connectionSocket.recv(1024)#Fill in start #Fill in end
       print "message: \n", message
       filename = message.split()[1]
       f = open(filename[1:])
       outputdata = f.read()
       print "outputdata:", outputdata
       now = datetime.datetime.now()
       #Fill in start #Fill in end
       #Send one HTTP header line into socket
       #Fill in start
       first_header = "HTTP/1.1 200 OK"
       # alive ={
       #    "timeout":10,
       #    "max":100,
       # }
       header_info = {
           "Date": now.strftime("%Y-%m-%d %H:%M"),
           "Content-Length": len(outputdata),
           "Keep-Alive": "timeout=%d,max=%d" %(10,100),
           "Connection": "Keep-Alive",
           "Content-Type": "text/html"
       }
      
       following_header = "\r\n".join("%s:%s" % (item, header_info[item]) for item in header_info)
       print "following_header:", following_header
       connectionSocket.send("%s\r\n%s\r\n\r\n" %(first_header, following_header))
       # connectionSocket.send("\r\n")
       # Date: %s\r\nKeep-Alive: timeout=10, max=100\r\n Connection: nKeep-Alive\r\n Content-Type: text/html;charset= utf-8" %(now.strftime("%Y-%m-%d %H:%m")))
       #Fill in end
       #Send the content of the requested file to the client
       for i in range(0, len(outputdata)):
           connectionSocket.send(outputdata[i])
       connectionSocket.close()
   except IOError:
       #Send response message for file not found
       #Fill in start
       connectionSocket.send("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!doctype html><html><body><h1>404 Not Found<h1></body></html>")
       #Fill in end
       #Close client socket
       #Fill in start
       connectionSocket.close()
       #Fill in end
serverSocket.close()


Related Solutions

You are evaluating orders from two customers but can accept only one of the orders because...
You are evaluating orders from two customers but can accept only one of the orders because of your company's limited capacity. the first order is for 100 units of a product with a contribution margin ratio of 60% and a selling price of $1,000. The second order is for 500 units of a product with a contribution margin ratio of 20% and a selling price of $800. The incremental fixed costs are the same for both orders. Which order should...
USE ONLY THE BELOW FUNCTIONS AND IMPLEMENT THE MISSING PART implement the following missing functions from...
USE ONLY THE BELOW FUNCTIONS AND IMPLEMENT THE MISSING PART implement the following missing functions from the implementation: * reset * intersection * difference Set Set::intersection(Set& s){ Set r; // find intersection return r; } Set Set::difference(Set& s){ Set r; // find difference return r; } void Set::reset(int c){ // increase the capacity and clear the data } driver program int a1[] = {10,5,7,3,9}; Set s1(5); s1.insert(a1,5); s1.print("s1"); int a2[] = {2,9,6}; Set s2(3); s2.insert(a2,3); s2.print("s2"); Set s3 = s1.unionset(s2);...
In C++, implement a class called setOper that provides several simple set operations. The class only...
In C++, implement a class called setOper that provides several simple set operations. The class only needs to deal with sets that are closed intervals specified by two real numbers; for example, the pair (2.5, 4.5) represent the interval [2.5, 4.5]. The following operations should be supported: - Check if the value x belongs to the given interval. - Check if the value x belongs to the intersection of two intervals. - Check if the value x belongs to the...
Part 2: Use MySQL Workbench to add a table to your database on the class server...
Part 2: Use MySQL Workbench to add a table to your database on the class server and name the table “Person”. Include these fields in the Person table: Field Name Description Data Type Sample Value LoginID User’s login name varchar(10) Bob FirstName User’s first name varchar(50) Bob LastName User’s last name varchar(50) Barker picUrl Filename of the user’s picture varchar(50) bob.gif Bio User’s biography varchar(255) Bob is the best! LoginID should be the Primary Key of the table. Add at...
QUESTION ONE Implementing changes in business planning is only part of a larger process of managing...
QUESTION ONE Implementing changes in business planning is only part of a larger process of managing major changes in business processes which employees do not like. State and explain five recommendations from change experts to minimize resistance.
Which one of the following is true if the managers of a firm accept only projects...
Which one of the following is true if the managers of a firm accept only projects that have a profitability index greater than 1.5? Group of answer choices The internal rate of return on each new project is zero. The net present value of each new project is zero. The price of the firm's stock should remain constant. The firm is most likely steadily losing value. The firm should increase in value each time it accepts a new project.
A limitation of the chat server is that it can handle only one client because it...
A limitation of the chat server is that it can handle only one client because it is a single threaded application. Using the pThread library, modify the chat server so that it can handle multiple clients simultaneously, i.e., by creating a new thread whenever a client is connected so that the client is handled individually with a new thread, and at the same time, by having the main thread (i.e., the thread that runs the main function) of the chat...
Function Template and Exception Handling In part one, you are going to implement the selection sort...
Function Template and Exception Handling In part one, you are going to implement the selection sort function that is capable of sorting vectors of int, double or string. In part two you will be writing a try catch block to catch the out-of-range exception. You are to write three functions and manipulate main() function for this lab all of which should be written in one main.cpp file: Part one: unsigned min_index(const vector<T> &vals, unsigned index): Passes in an index of...
I need to implement incrementalInserstionSort im stuck on that part import java.util.*; /** * This class...
I need to implement incrementalInserstionSort im stuck on that part import java.util.*; /** * This class represents chains of linked nodes that * can be sorted by a Shell sort. * * @author Charles Hoot * @author Frank M. Carrano * Modified by atb * @author YOUR NAME * @version 9/29/2020 */ public class ChainSort> { private Node firstNode; // reference to first node public ChainSort() { this.firstNode = null; } public void display() { Node currentNode = this.firstNode; while...
Implement the stack class (called Stack2) using queue, meaning that the only operations that can be...
Implement the stack class (called Stack2) using queue, meaning that the only operations that can be used are the ones defined in the Queue class. class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) The codes to fill: """ 1. Stack2 class Implement stack data structure using queue """ class Stack2: def __init__(self): # Write your definition for __init__ here def isEmpty(self): #...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT