SlideShare a Scribd company logo
Note: Use Java Write a web server that is capable of processing only 1 request. Your web server
will: Create a connection socket when contacted by the client (browser) Receive the HTTP
request from this connection Parse the request to determine the specific file being requested Get
the requested file from the server's file system Create an HTTP response message consisting of
the requested file Send the response over TCP Connection to the requesting browser If a client
requests a file that is not present in your server, your server should return a "404 Not Found"
error message.
Solution
For this problem we will create a UI using swings library. also we will create a separate
WebServer class for
the server implementation. We will run the server in a separate thread and for this we will use
Thread class.
Class UI:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/* this class contains A simple Swing UI.
* which has one start button and one txt console
*/
public class UI extends JFrame {
static Integer portNumber = null;
JPanel mainPanel;
JScrollPane scrollPane;
JButton btnStartServer;
JTextArea textArea_1;
public UI() {
mainPanel = new JPanel();
scrollPane = new JScrollPane();
btnStartServer = new JButton("Start Server");
btnStartServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
startServer();
}
});
getContentPane().add(btnStartServer, BorderLayout.SOUTH);
textArea_1 = new JTextArea();
textArea_1.setBackground(Color.BLACK);
textArea_1.setForeground(new Color(255, 255, 255));
textArea_1.setRows(30);
textArea_1.setColumns(30);
getContentPane().add(textArea_1, BorderLayout.CENTER);
textArea_1.setBorder(BorderFactory.createLoweredBevelBorder());
textArea_1.setEditable(false);
this.setTitle("Simple Web Server");
this.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(WindowEvent e) {
close(e);
}
});
scrollPane.setViewportView(textArea_1);
mainPanel.add(scrollPane);
this.getContentPane().add(mainPanel, BorderLayout.EAST);
this.setVisible(true);
this.setSize(350,300);
this.setResizable(false);
this.validate();
}
private void startServer() {
new WebServer(portNumber.intValue(), this);
}
void close(WindowEvent event) {
System.exit(1);
}
public void displayMessage(String s) {
textArea_1.append(s);
}
public static void main(String[] args) {
portNumber = new Integer(8080);
UI ui = new UI();
}
}
Class WebServer :
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer extends Thread {
private UI message_to; // need UI to display Message
private int portNumber; //need port to run on localhost
//Constructor, takes portNumber and UI as input
public WebServer(int portNumber, UI ui) {
this.message_to = ui;
this.portNumber = portNumber;
this.start();
}
// Thread implementation, overriding run method to run server in separate thread
public void run() {
ServerSocket socket = null;
sendMessage("Starting Server. . . ");
try {
sendMessage("Checking port " + Integer.toString(portNumber) + ". . . . . ");
socket = new ServerSocket(portNumber);
}
catch (Exception exception) {
sendMessage("Error:" + exception.getMessage());
return;
}
sendMessage("Started . . . ");
while (true) {
sendMessage("Ready and awaiting for requests. . . ");
try {
Socket cSocket = socket.accept();
InetAddress address = cSocket.getInetAddress();
sendMessage(address.getHostName() + " connected to server. ");
BufferedReader reader =new BufferedReader(new
InputStreamReader(cSocket.getInputStream()));
DataOutputStream outputStream =new
DataOutputStream(cSocket.getOutputStream());
serviceRequest(reader, outputStream);
}
catch (Exception exception) {
sendMessage(" Error:" + exception.getMessage());
}
}
}
private void serviceRequest(BufferedReader reader, DataOutputStream outputStream) {
boolean isGet=false;
String path = new String();
try {
String str1 = reader.readLine();
String str2 = new String(str1);
str1.toUpperCase();
if (str1.startsWith("GET")) {
isGet=true;
}else if (str1.startsWith("HEAD")) { //
}else {
try {
outputStream.writeBytes(constructHeader(501, 0));
outputStream.close();
return;
}
catch (Exception exception) {
sendMessage("Error:" + exception.getMessage());
}
}
int first = 0;
int last = 0;
for (int a = 0; a < str2.length(); a++) {
if (str2.charAt(a) == ' ' && first != 0) {
last = a;
break;
}
if (str2.charAt(a) == ' ' && first == 0) {
first = a;
}
}
path = str2.substring(first + 2, last);
}
catch (Exception exception) {
sendMessage("Error:" + exception.getMessage());
}
sendMessage(" Requested file:" + new File(path).getAbsolutePath() + " ");
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(path);
}
catch (Exception exception) {
try {
outputStream.writeBytes(constructHeader(404, 0));
outputStream.close();
}
catch (Exception e) {
sendMessage("Error: " + e.getMessage());
}
sendMessage("Error: " + exception.getMessage());
}
try {
int type = 0;
if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {
type = 1;
}else if (path.endsWith(".gif")) {
type = 2;
}else if (path.endsWith(".zip") || path.endsWith(".exe")|| path.endsWith(".tar")) {
type = 3;
}
outputStream.writeBytes(constructHeader(200, type));
if (isGet) {
while (true) {
int b = inputStream.read();
if (b == -1) {
break;
}
outputStream.write(b);
}
}
outputStream.close();
inputStream.close();
}
catch (Exception exception) {
sendMessage("Error: " + exception.getMessage());
}
}
private String constructHeader(int return_code, int type) {
String header = "HTTP/1.0 ";
switch (return_code) {
case 200:
header = header + "200 OK";
break;
case 404:
header = header + "404 Not Found";
break;
}
header = header + "  ";
header = header + "Connection: close  ";
header = header + "Server: SimpleWebServer v0  ";
switch (type) {
case 0:
break;
case 1:
header = header + "Content-Type: image/jpeg  ";
break;
case 2:
header = header + "Content-Type: image/gif  ";
case 3:
header = header + "Content-Type: application/x-zip-compressed  ";
default:
header = header + "Content-Type: text/html  ";
break;
}
header = header + "  ";
return header;
}
private void sendMessage(String message) {
message_to.displayMessage(message);
}
}

More Related Content

Similar to Note Use Java Write a web server that is capable of processing only.pdf

Jason parsing
Jason parsingJason parsing
Jason parsing
parallelminder
 
Multi client
Multi clientMulti client
Multi clientganteng8
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
fadlihulopi
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
Sivadon Chaisiri
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
meerobertsonheyde608
 
Code red SUM
Code red SUMCode red SUM
Code red SUM
Shumail Haider
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
Suman Astani
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdf
adinathassociates
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Divakar Gu
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
Yakov Fain
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
Manuela Grindei
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web development
Johannes Brodwall
 

Similar to Note Use Java Write a web server that is capable of processing only.pdf (20)

Jason parsing
Jason parsingJason parsing
Jason parsing
 
My java file
My java fileMy java file
My java file
 
Multi client
Multi clientMulti client
Multi client
 
java sockets
 java sockets java sockets
java sockets
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
 
Code red SUM
Code red SUMCode red SUM
Code red SUM
 
Bhaloo
BhalooBhaloo
Bhaloo
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdf
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Network
NetworkNetwork
Network
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web development
 

More from fatoryoutlets

Write an informal paper that is exactly 3 pages long not counting th.pdf
Write an informal paper that is exactly 3 pages long not counting th.pdfWrite an informal paper that is exactly 3 pages long not counting th.pdf
Write an informal paper that is exactly 3 pages long not counting th.pdf
fatoryoutlets
 
Write a C program to find factorial of an integer n, where the user .pdf
Write a C program to find factorial of an integer n, where the user .pdfWrite a C program to find factorial of an integer n, where the user .pdf
Write a C program to find factorial of an integer n, where the user .pdf
fatoryoutlets
 
When was the black body mutation in drosophila melanogaster discover.pdf
When was the black body mutation in drosophila melanogaster discover.pdfWhen was the black body mutation in drosophila melanogaster discover.pdf
When was the black body mutation in drosophila melanogaster discover.pdf
fatoryoutlets
 
What is it that consumer researchers try to find among varying cultu.pdf
What is it that consumer researchers try to find among varying cultu.pdfWhat is it that consumer researchers try to find among varying cultu.pdf
What is it that consumer researchers try to find among varying cultu.pdf
fatoryoutlets
 
What are pros and cons of Symantec endpoint security softwareSo.pdf
What are pros and cons of Symantec endpoint security softwareSo.pdfWhat are pros and cons of Symantec endpoint security softwareSo.pdf
What are pros and cons of Symantec endpoint security softwareSo.pdf
fatoryoutlets
 
All of the following describe the International Accounting Standard .pdf
All of the following describe the International Accounting Standard .pdfAll of the following describe the International Accounting Standard .pdf
All of the following describe the International Accounting Standard .pdf
fatoryoutlets
 
The right and left sternocleidomastoid muscles of humans originate o.pdf
The right and left sternocleidomastoid muscles of humans originate o.pdfThe right and left sternocleidomastoid muscles of humans originate o.pdf
The right and left sternocleidomastoid muscles of humans originate o.pdf
fatoryoutlets
 
The code in image3.cpp has the error as shown above, could you help .pdf
The code in image3.cpp has the error as shown above, could you help .pdfThe code in image3.cpp has the error as shown above, could you help .pdf
The code in image3.cpp has the error as shown above, could you help .pdf
fatoryoutlets
 
the ability of the cardiac muscle cells to fire on their own is .pdf
the ability of the cardiac muscle cells to fire on their own is .pdfthe ability of the cardiac muscle cells to fire on their own is .pdf
the ability of the cardiac muscle cells to fire on their own is .pdf
fatoryoutlets
 
Template LinkedList;I am using templates to make some linkedLists.pdf
Template LinkedList;I am using templates to make some linkedLists.pdfTemplate LinkedList;I am using templates to make some linkedLists.pdf
Template LinkedList;I am using templates to make some linkedLists.pdf
fatoryoutlets
 
Surface water entering the North Atlantic may have a temperature of .pdf
Surface water entering the North Atlantic may have a temperature of .pdfSurface water entering the North Atlantic may have a temperature of .pdf
Surface water entering the North Atlantic may have a temperature of .pdf
fatoryoutlets
 
Suppose the rate of plant growth on Isle Royale supported an equilib.pdf
Suppose the rate of plant growth on Isle Royale supported an equilib.pdfSuppose the rate of plant growth on Isle Royale supported an equilib.pdf
Suppose the rate of plant growth on Isle Royale supported an equilib.pdf
fatoryoutlets
 
Q1. public void operationZ() throws StackUnderflowException {   .pdf
Q1. public void operationZ() throws StackUnderflowException {   .pdfQ1. public void operationZ() throws StackUnderflowException {   .pdf
Q1. public void operationZ() throws StackUnderflowException {   .pdf
fatoryoutlets
 
Print Calculator Question 18 of 20 Sapling Learning Map do ment of Lu.pdf
Print Calculator Question 18 of 20 Sapling Learning Map do ment of Lu.pdfPrint Calculator Question 18 of 20 Sapling Learning Map do ment of Lu.pdf
Print Calculator Question 18 of 20 Sapling Learning Map do ment of Lu.pdf
fatoryoutlets
 
Part A 1. Solid product forms during the addition of the bleach solu.pdf
Part A 1. Solid product forms during the addition of the bleach solu.pdfPart A 1. Solid product forms during the addition of the bleach solu.pdf
Part A 1. Solid product forms during the addition of the bleach solu.pdf
fatoryoutlets
 
Only 15 of the carbon-14 in a wooden bowl remains. How old is the b.pdf
Only 15 of the carbon-14 in a wooden bowl remains. How old is the b.pdfOnly 15 of the carbon-14 in a wooden bowl remains. How old is the b.pdf
Only 15 of the carbon-14 in a wooden bowl remains. How old is the b.pdf
fatoryoutlets
 
Negotiations are not usually faster in Deal focused cultures than re.pdf
Negotiations are not usually faster in Deal focused cultures than re.pdfNegotiations are not usually faster in Deal focused cultures than re.pdf
Negotiations are not usually faster in Deal focused cultures than re.pdf
fatoryoutlets
 
9. The tort of assault and the tort of battery A) can occur independe.pdf
9. The tort of assault and the tort of battery A) can occur independe.pdf9. The tort of assault and the tort of battery A) can occur independe.pdf
9. The tort of assault and the tort of battery A) can occur independe.pdf
fatoryoutlets
 
Jj_numjnamecityj1SorterParisj2PunchRomej3Reade.pdf
Jj_numjnamecityj1SorterParisj2PunchRomej3Reade.pdfJj_numjnamecityj1SorterParisj2PunchRomej3Reade.pdf
Jj_numjnamecityj1SorterParisj2PunchRomej3Reade.pdf
fatoryoutlets
 
If law enforcement fails to give the defendant their Miranda rights,.pdf
If law enforcement fails to give the defendant their Miranda rights,.pdfIf law enforcement fails to give the defendant their Miranda rights,.pdf
If law enforcement fails to give the defendant their Miranda rights,.pdf
fatoryoutlets
 

More from fatoryoutlets (20)

Write an informal paper that is exactly 3 pages long not counting th.pdf
Write an informal paper that is exactly 3 pages long not counting th.pdfWrite an informal paper that is exactly 3 pages long not counting th.pdf
Write an informal paper that is exactly 3 pages long not counting th.pdf
 
Write a C program to find factorial of an integer n, where the user .pdf
Write a C program to find factorial of an integer n, where the user .pdfWrite a C program to find factorial of an integer n, where the user .pdf
Write a C program to find factorial of an integer n, where the user .pdf
 
When was the black body mutation in drosophila melanogaster discover.pdf
When was the black body mutation in drosophila melanogaster discover.pdfWhen was the black body mutation in drosophila melanogaster discover.pdf
When was the black body mutation in drosophila melanogaster discover.pdf
 
What is it that consumer researchers try to find among varying cultu.pdf
What is it that consumer researchers try to find among varying cultu.pdfWhat is it that consumer researchers try to find among varying cultu.pdf
What is it that consumer researchers try to find among varying cultu.pdf
 
What are pros and cons of Symantec endpoint security softwareSo.pdf
What are pros and cons of Symantec endpoint security softwareSo.pdfWhat are pros and cons of Symantec endpoint security softwareSo.pdf
What are pros and cons of Symantec endpoint security softwareSo.pdf
 
All of the following describe the International Accounting Standard .pdf
All of the following describe the International Accounting Standard .pdfAll of the following describe the International Accounting Standard .pdf
All of the following describe the International Accounting Standard .pdf
 
The right and left sternocleidomastoid muscles of humans originate o.pdf
The right and left sternocleidomastoid muscles of humans originate o.pdfThe right and left sternocleidomastoid muscles of humans originate o.pdf
The right and left sternocleidomastoid muscles of humans originate o.pdf
 
The code in image3.cpp has the error as shown above, could you help .pdf
The code in image3.cpp has the error as shown above, could you help .pdfThe code in image3.cpp has the error as shown above, could you help .pdf
The code in image3.cpp has the error as shown above, could you help .pdf
 
the ability of the cardiac muscle cells to fire on their own is .pdf
the ability of the cardiac muscle cells to fire on their own is .pdfthe ability of the cardiac muscle cells to fire on their own is .pdf
the ability of the cardiac muscle cells to fire on their own is .pdf
 
Template LinkedList;I am using templates to make some linkedLists.pdf
Template LinkedList;I am using templates to make some linkedLists.pdfTemplate LinkedList;I am using templates to make some linkedLists.pdf
Template LinkedList;I am using templates to make some linkedLists.pdf
 
Surface water entering the North Atlantic may have a temperature of .pdf
Surface water entering the North Atlantic may have a temperature of .pdfSurface water entering the North Atlantic may have a temperature of .pdf
Surface water entering the North Atlantic may have a temperature of .pdf
 
Suppose the rate of plant growth on Isle Royale supported an equilib.pdf
Suppose the rate of plant growth on Isle Royale supported an equilib.pdfSuppose the rate of plant growth on Isle Royale supported an equilib.pdf
Suppose the rate of plant growth on Isle Royale supported an equilib.pdf
 
Q1. public void operationZ() throws StackUnderflowException {   .pdf
Q1. public void operationZ() throws StackUnderflowException {   .pdfQ1. public void operationZ() throws StackUnderflowException {   .pdf
Q1. public void operationZ() throws StackUnderflowException {   .pdf
 
Print Calculator Question 18 of 20 Sapling Learning Map do ment of Lu.pdf
Print Calculator Question 18 of 20 Sapling Learning Map do ment of Lu.pdfPrint Calculator Question 18 of 20 Sapling Learning Map do ment of Lu.pdf
Print Calculator Question 18 of 20 Sapling Learning Map do ment of Lu.pdf
 
Part A 1. Solid product forms during the addition of the bleach solu.pdf
Part A 1. Solid product forms during the addition of the bleach solu.pdfPart A 1. Solid product forms during the addition of the bleach solu.pdf
Part A 1. Solid product forms during the addition of the bleach solu.pdf
 
Only 15 of the carbon-14 in a wooden bowl remains. How old is the b.pdf
Only 15 of the carbon-14 in a wooden bowl remains. How old is the b.pdfOnly 15 of the carbon-14 in a wooden bowl remains. How old is the b.pdf
Only 15 of the carbon-14 in a wooden bowl remains. How old is the b.pdf
 
Negotiations are not usually faster in Deal focused cultures than re.pdf
Negotiations are not usually faster in Deal focused cultures than re.pdfNegotiations are not usually faster in Deal focused cultures than re.pdf
Negotiations are not usually faster in Deal focused cultures than re.pdf
 
9. The tort of assault and the tort of battery A) can occur independe.pdf
9. The tort of assault and the tort of battery A) can occur independe.pdf9. The tort of assault and the tort of battery A) can occur independe.pdf
9. The tort of assault and the tort of battery A) can occur independe.pdf
 
Jj_numjnamecityj1SorterParisj2PunchRomej3Reade.pdf
Jj_numjnamecityj1SorterParisj2PunchRomej3Reade.pdfJj_numjnamecityj1SorterParisj2PunchRomej3Reade.pdf
Jj_numjnamecityj1SorterParisj2PunchRomej3Reade.pdf
 
If law enforcement fails to give the defendant their Miranda rights,.pdf
If law enforcement fails to give the defendant their Miranda rights,.pdfIf law enforcement fails to give the defendant their Miranda rights,.pdf
If law enforcement fails to give the defendant their Miranda rights,.pdf
 

Recently uploaded

Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
DhatriParmar
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 

Recently uploaded (20)

Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 

Note Use Java Write a web server that is capable of processing only.pdf

  • 1. Note: Use Java Write a web server that is capable of processing only 1 request. Your web server will: Create a connection socket when contacted by the client (browser) Receive the HTTP request from this connection Parse the request to determine the specific file being requested Get the requested file from the server's file system Create an HTTP response message consisting of the requested file Send the response over TCP Connection to the requesting browser If a client requests a file that is not present in your server, your server should return a "404 Not Found" error message. Solution For this problem we will create a UI using swings library. also we will create a separate WebServer class for the server implementation. We will run the server in a separate thread and for this we will use Thread class. Class UI: import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.WindowEvent; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; /* this class contains A simple Swing UI. * which has one start button and one txt console */ public class UI extends JFrame { static Integer portNumber = null; JPanel mainPanel; JScrollPane scrollPane; JButton btnStartServer; JTextArea textArea_1;
  • 2. public UI() { mainPanel = new JPanel(); scrollPane = new JScrollPane(); btnStartServer = new JButton("Start Server"); btnStartServer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { startServer(); } }); getContentPane().add(btnStartServer, BorderLayout.SOUTH); textArea_1 = new JTextArea(); textArea_1.setBackground(Color.BLACK); textArea_1.setForeground(new Color(255, 255, 255)); textArea_1.setRows(30); textArea_1.setColumns(30); getContentPane().add(textArea_1, BorderLayout.CENTER); textArea_1.setBorder(BorderFactory.createLoweredBevelBorder()); textArea_1.setEditable(false); this.setTitle("Simple Web Server"); this.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(WindowEvent e) { close(e); } }); scrollPane.setViewportView(textArea_1); mainPanel.add(scrollPane); this.getContentPane().add(mainPanel, BorderLayout.EAST); this.setVisible(true); this.setSize(350,300); this.setResizable(false); this.validate(); } private void startServer() {
  • 3. new WebServer(portNumber.intValue(), this); } void close(WindowEvent event) { System.exit(1); } public void displayMessage(String s) { textArea_1.append(s); } public static void main(String[] args) { portNumber = new Integer(8080); UI ui = new UI(); } } Class WebServer : import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class WebServer extends Thread { private UI message_to; // need UI to display Message private int portNumber; //need port to run on localhost //Constructor, takes portNumber and UI as input public WebServer(int portNumber, UI ui) { this.message_to = ui; this.portNumber = portNumber; this.start(); } // Thread implementation, overriding run method to run server in separate thread public void run() { ServerSocket socket = null; sendMessage("Starting Server. . . ");
  • 4. try { sendMessage("Checking port " + Integer.toString(portNumber) + ". . . . . "); socket = new ServerSocket(portNumber); } catch (Exception exception) { sendMessage("Error:" + exception.getMessage()); return; } sendMessage("Started . . . "); while (true) { sendMessage("Ready and awaiting for requests. . . "); try { Socket cSocket = socket.accept(); InetAddress address = cSocket.getInetAddress(); sendMessage(address.getHostName() + " connected to server. "); BufferedReader reader =new BufferedReader(new InputStreamReader(cSocket.getInputStream())); DataOutputStream outputStream =new DataOutputStream(cSocket.getOutputStream()); serviceRequest(reader, outputStream); } catch (Exception exception) { sendMessage(" Error:" + exception.getMessage()); } } } private void serviceRequest(BufferedReader reader, DataOutputStream outputStream) { boolean isGet=false; String path = new String(); try { String str1 = reader.readLine(); String str2 = new String(str1); str1.toUpperCase(); if (str1.startsWith("GET")) { isGet=true; }else if (str1.startsWith("HEAD")) { //
  • 5. }else { try { outputStream.writeBytes(constructHeader(501, 0)); outputStream.close(); return; } catch (Exception exception) { sendMessage("Error:" + exception.getMessage()); } } int first = 0; int last = 0; for (int a = 0; a < str2.length(); a++) { if (str2.charAt(a) == ' ' && first != 0) { last = a; break; } if (str2.charAt(a) == ' ' && first == 0) { first = a; } } path = str2.substring(first + 2, last); } catch (Exception exception) { sendMessage("Error:" + exception.getMessage()); } sendMessage(" Requested file:" + new File(path).getAbsolutePath() + " "); FileInputStream inputStream = null; try { inputStream = new FileInputStream(path); } catch (Exception exception) { try { outputStream.writeBytes(constructHeader(404, 0)); outputStream.close(); }
  • 6. catch (Exception e) { sendMessage("Error: " + e.getMessage()); } sendMessage("Error: " + exception.getMessage()); } try { int type = 0; if (path.endsWith(".jpg") || path.endsWith(".jpeg")) { type = 1; }else if (path.endsWith(".gif")) { type = 2; }else if (path.endsWith(".zip") || path.endsWith(".exe")|| path.endsWith(".tar")) { type = 3; } outputStream.writeBytes(constructHeader(200, type)); if (isGet) { while (true) { int b = inputStream.read(); if (b == -1) { break; } outputStream.write(b); } } outputStream.close(); inputStream.close(); } catch (Exception exception) { sendMessage("Error: " + exception.getMessage()); } } private String constructHeader(int return_code, int type) { String header = "HTTP/1.0 "; switch (return_code) { case 200:
  • 7. header = header + "200 OK"; break; case 404: header = header + "404 Not Found"; break; } header = header + " "; header = header + "Connection: close "; header = header + "Server: SimpleWebServer v0 "; switch (type) { case 0: break; case 1: header = header + "Content-Type: image/jpeg "; break; case 2: header = header + "Content-Type: image/gif "; case 3: header = header + "Content-Type: application/x-zip-compressed "; default: header = header + "Content-Type: text/html "; break; } header = header + " "; return header; } private void sendMessage(String message) { message_to.displayMessage(message); } }