/* * Skeleton program for Web Server assignment. * The server dies after handlin
ID: 3824642 • Letter: #
Question
/*
* Skeleton program for Web Server assignment.
* The server dies after handling one request. Fix it
* to run indefinitely, handling multiple sequential
* requests
*
*
*/
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class WebServer {
public static void main(String[] args) {
/*
* Step 1: We need to create a Server that handles the requests from browser. For creating a
* java server, we need to find out an unoccupied port. All the ports from 1 to 999 are assigned
* to some of the well known application. So, if you want to create your own server, assign the
* server port 4 or 5 digit number. For example, in this case I am using 7777 as port number.
* Now for creating a server, first we need to create server socket that will listen the port
* 7777.
*/
int port = 7777;
ServerSocket server = null;
try{
server = new ServerSocket(port);
/*
* My server is created at this point. Now the server will listen for one client connection.
* The server will start listening when you call the accept() method. When the server receives
* a client's connection request, the accept() method returns a Socket instance of that
* client.
*/
System.out.println("Server is waiting for a client...");
/*There are six steps in the Web Server assignment. I've pointed out each step and left blank
* some steps. You are responsible to complete those steps.
*/
/*
* =====================================================================
* Step 1: create a connection socket when contacted by a client browser
* =====================================================================
*/
Socket client = server.accept();
System.out.println("Server is connected to a client!");
/*
* At this point, a client is connected to the server. Now, we need to read the client's
* request. Since the client is a web browser in the assignment and the browser's request
* is a HTTP get request, the server will receive a request like below:
* This is an example. You might see more or less fields. But that doesn't create any issue,
* because we only need the request line (the first line is the request line).
* ========================================================================================
GET /wireshark-labs/HTTP-wireshark-file1.html HTTP/1.1
Host: gaia.cs.umass.edu
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*//*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
*=========================================================================================
* Now, we need to read the client's input stream in order to get the HTTP header request.
* We can get the client's input stream by using the getInputSteam() method.
*/
//Now we will create a buffer reader to read from the input stream
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
/*
* =====================================================
* Step 2: receive the HTTP request from this connection
* =====================================================
*/
//All the HTTP Request header content is read here
String line = br.readLine();
while((line = br.readLine()).length() != 0){
System.out.println(line);
}
/*
* ========================================================================
* Step 3: parse the request to determine the specific file being requested
* ========================================================================
* To do: You are responsible to complete this step
*/
/*
* ============================================================
* Step 4: get the requested file from the server's file system
* ============================================================
* To do: You are responsible to complete this step
*/
/*
* =================================================================================================
* Step 5: create an HTTP response message consisting of the requested file preceded by header lines
* =================================================================================================
* An example of the HTTP response header is the following:
* ========================================================
HTTP/1.1 200 OK
Date: Sat, 17 Sep 2016 04:23:38 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.1e-fips PHP/5.4.16 mod_perl/2.0.9dev Perl/v5.16.3
Last-Modified: Fri, 16 Sep 2016 05:59:01 GMT
ETag: "80-53c99a8b5bfcc"
Accept-Ranges: bytes
Content-Length: 128
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
*===========================================================
* I am creating a HTTP Response header when the requested file is not existed in the server,
* i.e., a Not Found HTTP Response header, with the content 'File Not Found' text.
* You are responsible for completing the part when a file present in server file system
*/
boolean fileExist = false;
String responseMsg = "";
if(fileExist){
//Read from the file and generate the HTTP Response message with the file content
}else{
responseMsg += "HTTP/1.1 404 Not Found ";
responseMsg += "Content-Type: text/html ";
responseMsg += " ";
responseMsg += "<html><head><title>Page Not Found</title></head><body><h1>The request page is not found!</h1></body></html>";
}
/*
* ===========================================================================
* Step 6: send the response over the TCP connection to the requesting browser
* ===========================================================================
* Now in order to send the response back to the client browser, we need to write
* the response message to the client's output stream.
*/
System.out.println(responseMsg);
DataOutputStream outToClient = new DataOutputStream(client.getOutputStream());
sendBytes(responseMsg, outToClient);
br.close();
outToClient.close();
client.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
/*
* This method is used for writing the content to the output stream.
* Uses:
* param1: the message you want to write
* param2: the data output stream
*/
private static void sendBytes(String message, OutputStream os) throws Exception{
InputStream is = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
byte[] buffer = new byte[1024];
int bytes = 0;
while((bytes = is.read(buffer)) != -1){
os.write(buffer, 0, bytes);
}
}
}
Explanation / Answer
Server.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSock1et;
import java.net.Sock1et;
public class Server {
public final static int SOCK1ET_PORT = 2000; // you may change this
public final static String FILE_TO_SEND = " D:chegg.txt"; // you may change this
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSock1et servsock1 = null;
Sock1et sock1 = null;
try {
servsock1 = new ServerSock1et(SOCK1ET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock1 = servsock1.accept();
System.out.println("Accepted connection : " + sock1);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock1.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock1!=null) sock1.close();
}
}
}
finally {
if (servsock1 != null) servsock1.close();
}
}
}
Client.java
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.