i've been working on a simple HTTP web server in java. however i seem to be running into an issue where when i try to get the file name in the request i get an array out of bounds error even though its not out of bounds and i can clearly see it in the array. can anyone help code is below
public static void main(String[]args) throws Exception{
ServerSocket ss = new ServerSocket(8080);
while(true){
Socket s= ss.accept();
String ip = s.getInetAddress().toString();
ConnectionHandler ch = new ConnectionHandler(s);
ch.start();
System.out.println(ip);
}
public class ConnectionHandler extends Thread{
private Socket s;
private PrintWriter pw;
private BufferedReader br;
public ConnectionHandler(Socket s) throws Exception{
this.s = s;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream());
}
#Override
public void run(){
String reqs = "";
try {
while(br.ready()){
reqs += (char) br.read();
//System.out.println(reqs);
HttpRequest hr = new HttpRequest(reqs);
HttpResponse res = new HttpResponse(hr);
pw.write(res.response.toCharArray());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
pw.close();
try {
br.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class HttpRequest {
String fileName;
public HttpRequest(String reqs){
String lines[] = reqs.split("\n");
//System.out.println(lines[0]);
String lines1[] = lines[0].split(" ");
for(int i = 0;i<lines1.length;i++){
System.out.println(i + lines1[i]);
}
fileName = lines1[1]; //error is here
}
}
public class HttpResponse {
private HttpRequest req;
String response;
private String root="H:/root";
private FileInputStream fis;
private File f;
public HttpResponse(HttpRequest hr) throws Exception {
req = hr;
if(req.fileName == null){
f = new File("H:/root/helloworld.html");
fis = new FileInputStream(f);
}else{
f = new File(root + req.fileName);
fis = new FileInputStream(f);
}
response = "HTTP/1.1 200";
response += "content-type: text/html \r\n";
response += "Connection: close \r\n";
response += "content-length: " + f.length() + "\r\n";
response += "\r\n";
int s;
while((s=fis.read())!=-1){
response += (char) s;
}
fis.close();
}
}
The problem is that:
reqs += (char) br.read();
only reads a single char from the input and after each read character you try to parse the request.
So you will end up in a situation where you only have "G" in reqs which would cause lines1 to be of length 1. lines1[1] would try to access the second element in that array, which doesn't exist.
Try moving the parsing of the request outside of the loop.
[EDIT] Better formatting support in the answers. This works as intended for me.
while (br.ready()) {
reqs += (char) br.read();
}
HttpRequest hr = new HttpRequest(reqs);
HttpResponse res = new HttpResponse(hr);
pw.write(res.response.toCharArray());
Related
Have a task to create a basic http server. I've gotten to the point where it asks you to send text response back that should be displayed in your browser if you go to http://localhost:8080/ but I just get a page cannot be displayed error. I think it must be something to do with the format of the response I'm sending but i just can't get it. Any help would be much appreciated.
import java.net.*;
import java.io.*;
import java.util.*;
class HttpServer{
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(8080);
while(true){
HttpServerSession sesh = new HttpServerSession(ss.accept());
sesh.start();
}
}catch(IOException e){
System.err.println("IOException");
}
}
}
class HttpServerSession extends Thread {
private Socket client;
public HttpServerSession(Socket client){
this.client = client;
}
private void println(BufferedOutputStream bos, String s) throws IOException {
String news = s + "\r\n";
byte[] array = news.getBytes();
for(int i = 0; i < array.length; i++){
bos.write(array[i]);
}
return;
}
public void run(){
try{
InetAddress clientIP = client.getInetAddress();
System.out.println("We just got a message! " + clientIP.getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String request = reader.readLine();
System.out.println(request);
String[] parts = request.split(" ");
if(parts.length == 3){
BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
String filename = parts[1].substring(1);
if(parts[0].equals("GET")){
while(true){
String line = reader.readLine();
System.out.println(line);
if(line == null || line.equals("")){
break;
}
}
println(bos, "OK");
println(bos, "");
println(bos, "Hello World");
}
}
client.close();
}catch(Exception e){
System.err.println("Exception in thread");
}
}
}
Turns out I just had to flush the BufferedOutputStream
I'm trying to develop a client-server exchange program, and when I try to send data from client to server, I'm running into a SocketException. I've looked at other answers but none of them fit my exact case; I have two calls to osw.write, and only one of them works.
Client:
package me.primesearch.client;
import java.math.BigInteger;
import java.net.*;
import java.io.*;
public class PrimeSearchClient {
public static void main(String[] args) throws IOException{
Socket connection = null;
try{
/** Define a host server */
String host = "localhost";
/** Define a port */
int port = 25564;
StringBuffer instr = new StringBuffer();
System.out.println("SocketClient initialized");
/** Obtain an address object of the server */
InetAddress address = InetAddress.getByName(host);
/** Establish a socket connetion */
connection = new Socket(address, port);
/** Instantiate a BufferedOutputStream object */
BufferedOutputStream bos = new BufferedOutputStream(connection.
getOutputStream());
/** Instantiate a BufferedInputStream object for reading
/** Instantiate a BufferedInputStream object for reading
* incoming socket streams.
*/
BufferedInputStream bis = new BufferedInputStream(connection.
getInputStream());
/**Instantiate an InputStreamReader with the optional
* character encoding.
*/
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
/**Read the socket's InputStream and append to a StringBuffer */
int c;
/** Instantiate an OutputStreamWriter object with the optional character
* encoding.
*/
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
while(true){
String process = "drq " + (char) 13;
/** Write across the socket connection and flush the buffer */
osw.write(process);
osw.flush();
while ( (c = isr.read()) != 13)
instr.append( (char) c);
for(int i=0;i<50;i++){
BigInteger offset=new BigInteger(instr.toString()).add(BigInteger.valueOf(i));
if(isProbablyPrime(offset)){
process = "pri" + " " + offset + " " + (offset.divide(new BigInteger("50"))).toString() + (char) 13;
System.out.println(process);
/** Write across the socket connection and flush the buffer */
osw.write(process); //This doesn't work
osw.flush();
System.out.println("Prime found at " + offset);
}
}
}
} catch(IOException e) {
e.printStackTrace();
} finally {
connection.close();
}
}
public static boolean isProbablyPrime(BigInteger n) {
if(n.longValue()!=0){
BigInteger lessOne = n.subtract(BigInteger.ONE);
// get the next prime from one less than number and check with the number
return lessOne.nextProbablePrime().compareTo(n) == 0;
}
return false;
}
}
Server:
package me.primesearch.server;
import java.net.*;
import java.io.*;
public class PrimeSearchServer implements Runnable {
private Socket connection;
#SuppressWarnings("unused")
private int ID;
PrimeSearchServer(Socket s, int i) {
this.connection = s;
this.ID = i;
}
#SuppressWarnings("resource")
public static void main(String[] args) {
int port = 25564;
int count = 0;
try{
ServerSocket socket1 = new ServerSocket(port);
System.out.println("MultipleSocketServer Initialized");
while (true) {
Socket connection = socket1.accept();
Runnable runnable = new PrimeSearchServer(connection, ++count);
Thread thread = new Thread(runnable);
thread.start();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(is);
int character;
StringBuffer process = new StringBuffer();
while((character = isr.read()) != 13) {
process.append((char)character);
}
System.out.println(process);
String returnCode="0";
if(process.toString().split(" ")[0].equals("drq")){
System.out.println("Job request recieved");
File file = new File("packages.txt");
//Process input
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
String prevLine="";
boolean i = false;
int count=0;
while ((line = br.readLine()) != null) {
System.out.println("Looking for a package to send");
// process the line.
if(line.equals("0")){
System.out.println("Sending package " + count);
returnCode = Integer.toString(count);
i = true;
break;
}
prevLine = line;
count++;
System.out.println("No packages found");
}
if(!i){
returnCode = prevLine;
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("packages.txt", true)))) {
System.out.println("Creating new package");
out.println("0");
returnCode=Integer.toString(count);
}catch (IOException e) {
e.printStackTrace();
}
}
}
} else if (process.toString().split(" ")[0].equals("pri")){
System.out.println("Prime request recieved");
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("primes.txt", true)))) {
out.println(Integer.parseInt(process.toString().split(" ")[1]));
}catch (IOException e) {
e.printStackTrace();
}
updateLine(Integer.parseInt(process.toString().split(" ")[2]));
}
BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
osw.write(returnCode + (char)13);
osw.flush();
process = new StringBuffer();
}
catch (Exception e) {
System.out.println(e);
}
finally {
try {
connection.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
private void updateLine(int lines) throws IOException {
String data="packages.txt";
BufferedReader file = new BufferedReader(new FileReader(data));
String input = "";
String line;
for(int i=0;i<lines;i++){
input+=file.readLine()+System.lineSeparator();
}
file.readLine();
while ((line = file.readLine()) != null)
input += line + System.lineSeparator();
FileOutputStream os = new FileOutputStream(data);
os.write(input.getBytes());
file.close();
os.close();
}
}
Sorry if the indenting on the code looks a bit strange, I'm not used to using stack overflow.
You are closing the socket in your server class:
finally {
try {
connection.close();
}
catch (IOException e){
e.printStackTrace();
}
}
I think this is the problem. This is the first message you're sending to the server.
Client
String process = "drq " + (char) 13;
osw.write(process);
osw.flush();
And since your server stops reading after it gets a 13 char it closes the connection after it reads the first message.
Server
while((character = isr.read()) != 13) {
process.append((char)character);
}
I was getting the same exception when running functional test using TestNG. For me it was a version issue. Uninstalling it and installing older version fixed my issue. Read the following post for information.
https://github.com/cbeust/testng-eclipse/issues/91
I am making a simple ftp client/server program which on command from the clients lists files, tells the current directory, downloads files
My client code works fine since i have already tested it with a working server. However the server that i have designed gets stuck in the run() function on the line String message = br.readline(); If instead i use the br.read(), then it works but i need command in form of a string to know which file i have to download whereas br.read() returns int. Here's my code, i have used threading.
public class Myserver {
static final int PortNumber = 108;
static ServerSocket MyService;
static Socket clientSocket = null;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File directory;
directory = new File(System.getProperty("user.home"));
try {
MyService = new ServerSocket(PortNumber);
String cd = directory.toString();
System.out.println(cd);
System.out.println("Listening on " + PortNumber);
while(true) {
clientSocket = MyService.accept();
Connecthandle a = new Connecthandle(clientSocket, directory);
a.run();
}
}
catch (IOException e) {
System.out.println(e);
}
}
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
// Works Fine
void listfiles() throws IOException {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
GoingOut.close();
}
// Works Fine
void currentdirectory() throws IOException {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
GoingOut.close();
System.exit(0);
}
void sendfiles(String fileName) {
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader br = new BufferedReader(new FileReader(nfile));
String line;
while ((line = br.readLine()) != null) {
line = br.readLine();
GoingOut.writeBytes(line+"\n");
}
GoingOut.flush();
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
}
#SuppressWarnings("deprecation")
public void run() {
try {
DataInputStream comingin = new DataInputStream(clientsocket.getInputStream());
InputStreamReader isr = new InputStreamReader(comingin, "UTF-8");
BufferedReader br = new BufferedReader(isr);
System.out.println("here");
// if (br.ready())
String message = br.readLine(); // Code gets stuck here, if i use br.read() it works, but i need string output.
if (message.equals("listfiles\n")) {
listfiles();
} else if (message.equals("pwd")) {
currentdirectory();
} else if (message.contains("getfile,")) {
String fileName = new String(message.substring(8, message.length()));
sendfiles(fileName);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
clientsocket.close();
} catch (IOException e) {}
}
}
}
}
If readLine() is blocking and you are sending data, you aren't sending a newline.
I have the following problem....
try
{
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream()));
while(true)
{
String clientRequest = "";
String tempStr = clientInput.readLine();
while(tempStr != null && !tempStr.equals("null"))
{
System.out.println(tempStr);
clientRequest += tempStr + " ";
tempStr = clientInput.readLine();
}
//Parse Request
ArrayList<String> tokenArray = parseRequest(clientRequest);
Calendar c = Calendar.getInstance();
switch(tokenArray.get(0))
{
case "GET":
{
clientOutput.write("HTTP/1.1 200 OK\r\n");
clientOutput.write("Date: " + c.getDisplayName(0, Calendar.LONG, Locale.UK).toString() + "\r\n");
clientOutput.write("Server: Java HTTP Server v1.0\r\n");
clientOutput.flush();
break;
//Write File
}
default:
{
clientOutput.write("500\r\n");
clientOutput.flush();
}
}
}
}
Every thing works completely fine up-and-till the clientOutput.write("HTTP....... line,
the client just keeps waiting and waiting... i've attempted to flush after every sucsessive write and yet nothing..... BUT This is the weird part - if i write to and flush before the code enters the while-loop the the writes in the case "GET": works perfectly...... ie
The code does execute all the way to the
clientOutput.flush();
break;
//Write File
.
try
{
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream()));
clientOutput.write("HTTP/1.1 200 OK\r\n");
clientOutput.flush();
while(true)
{
String clientRequest = "";
String tempStr = clientInput.readLine();
while(tempStr != null && !tempStr.equals("null"))
{
System.out.println(tempStr);
clientRequest += tempStr + " ";
tempStr = clientInput.readLine();
}
//Parse Request
ArrayList<String> tokenArray = parseRequest(clientRequest);
Calendar c = Calendar.getInstance();
switch(tokenArray.get(0))
{
case "GET":
{
clientOutput.write("HTTP/1.1 200 OK\r\n");
clientOutput.write("Date: " + c.getDisplayName(0, Calendar.LONG, Locale.UK).toString() + "\r\n");
clientOutput.write("Server: Java HTTP Server v1.0\r\n");
clientOutput.flush();
break;
//Write File
}
Here is the code for the client
Socket s = new Socket("localhost", 1337);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter toServer = new BufferedWriter(new PrintWriter(s.getOutputStream()));
toServer.write("GET index.html HTTP/1.1\r\n");
toServer.write("HOST: 127.0.0.1\r\n");
toServer.write("Connection: close\r\n");
toServer.write("\r\n");
toServer.write("null\r\n");
toServer.flush();
while(true)
{
String ss = fromServer.readLine();
if(ss != null && !ss.equals("null"))
System.out.println(ss);
}
Server Class: Strydom_A_201103578_P03
public class Strydom_A_201103578_P03
{
Thread[] threadArray = new Thread[5];
int ClientCount = 0;
public Strydom_A_201103578_P03() throws ClientSizeExceededException
{
ServerSocket httpServer = null;
try
{
httpServer = new ServerSocket(1337);
}
catch (IOException ex)
{
Logger.getLogger(Strydom_A_201103578_P03.class.getName()).log(Level.SEVERE, null, ex);
}
while(true)
{
try
{
//Wait for connection
Socket clientSocket = httpServer.accept();
if(ClientCount < 5)
{
threadArray[ClientCount] = new Thread(new clientHandler(clientSocket));
threadArray[ClientCount].start();
ClientCount++;
}
else
{
throw new ClientSizeExceededException();
}
}
catch(IOException ex)
{
}
finally
{
}
}
}
class clientHandler implements Runnable
{
Socket clientSocket;
public clientHandler(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
#Override
public void run()
{
BufferedReader clientInput = null;
BufferedWriter clientOutput = null;
try
{
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream()));
clientOutput.write(" ");
clientOutput.flush();
while(true)
{
String clientRequest = "";
String tempStr = clientInput.readLine();
while(tempStr != null && !tempStr.equals("null"))
{
System.out.println(tempStr);
clientRequest += tempStr + " ";
tempStr = clientInput.readLine();
}
//Parse Request
ArrayList<String> tokenArray = parseRequest(clientRequest);
Calendar c = Calendar.getInstance();
switch(tokenArray.get(0))
{
case "GET":
{
clientOutput.write("HTTP/1.1 200 OK\r\n");
clientOutput.write("Date: " + c.getDisplayName(0, Calendar.LONG, Locale.UK).toString() + "\r\n");
clientOutput.write("Server: Java HTTP Server v1.0\r\n");
clientOutput.flush();
break;
//Write File
}
default:
{
clientOutput.write("500\r\n");
clientOutput.flush();
}
}
}
}
catch (IOException ex)
{
Logger.getLogger(Strydom_A_201103578_P03.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
try
{
clientInput.close();
clientOutput.close();
}
catch (IOException ex)
{
Logger.getLogger(Strydom_A_201103578_P03.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private ArrayList<String> parseRequest(String tempStr)
{
StringTokenizer httpTokens = new StringTokenizer(tempStr, " ");
ArrayList<String> tokens = new ArrayList<>();
while(httpTokens.hasMoreTokens())
tokens.add(httpTokens.nextToken());
return tokens;
}
}
public static void main(String[] args) throws ClientSizeExceededException
{
new Strydom_A_201103578_P03();
}
}
public class TestClient
{
public TestClient()
{
try
{
Socket s = new Socket("localhost", 1337);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter toServer = new BufferedWriter(new PrintWriter(s.getOutputStream()));
toServer.write("GET index.html HTTP/1.1\r\n");
toServer.write("HOST: 127.0.0.1\r\n");
toServer.write("Connection: close\r\n");
toServer.write("\r\n");
toServer.write("null\r\n");
toServer.flush();
while(true)
{
String ss = fromServer.readLine();
if(ss != null && !ss.equals("null"))
System.out.println(ss);
}
}
catch (UnknownHostException ex)
{
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args)
{
new TestClient();
}
}
Client Class: TestClient
Create a project( or 2) and run the files
The problem here is the PrintWriter. It swallows exceptions. Change it to an OutputStreamWriter. Then you will see any exception that is being swallowed. In general you should avoid PrintWriters and PrintOutputStreams over a network. They swallow exceptions that you need to know about.
You need to change your inner while loop to look for the end of the client's request:
while(tempStr != null && !tempStr.equals("null"))
to:
while(tempStr != null && !tempStr.equals("null") && !tempStr.equals(""))
The client won't disconnect (causing a null) after it sends a request. It will give you a blank line to indicate the end of its request.
Reason why returning the response header right away is working? Maybe the client just reads the 200 and (eventually) disconnects? So when you are reading the client's request, it ends and you get a null eventually.
EDIT:
So running your code, it works fine for me. Both the client and server are sending and receiving both requests and responses. However, the server never disconnects (the client includes a Connection: close header) and the client continues to block on readLine(). Unsurprisinly, when I include the write() and flush() immediately after setting up the connection on the server-side nothing changes except I see HTTP/1.1 200 OK twice on the client's end. Maybe all you need to do is close the clientSocket in a finally{} block at the end of your try/catch{}?
So for the futhering of my now ended suffering - here is what i finally did....
I changed both the server and the clients readers from BufferedReader/Writer to DataInputstream/OutputStream.... And it works perfectly now - ! Thanks to everyone
Aiden
Just do this and it will work..........
Add true as the 2nd parameter in the PrintWriter
clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream(), true));
I wrote this HttpRequest method, but for some reason it always goes to 404 Not Found, even though the file location exists when the java process isn't running.
import java.io.*;
import java.net.*;
import java.util.*;
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n";
Socket socket;
// Constructor
public HttpRequest(Socket socket) throws Exception {
this.socket = socket;
}
// Implement the run() method of the Runnable interface.
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 ) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if(fileName.endsWith(".jpeg") || fileName.endsWith(".jpg")) {
return "image/jpeg";
}
if(fileName.endsWith(".gif")) {
return "image/gif";
}
return "application/octet-stream";
}
private void processRequest() throws Exception {
// Get a reference to the socket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Set up input stream filters.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Get the request line of the HTTP request message.
String requestLine = new String(br.readLine());
// Display the request line.
System.out.println();
System.out.println(requestLine);
// Get and display the header lines.
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory.
fileName = "." + fileName;
// Open the requested file.
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "200 OK" + CRLF;
contentTypeLine = "Content-type: " +
contentType( fileName ) + CRLF;
} else {
statusLine = "404 NOT FOUND" + CRLF;
contentTypeLine = "Content Not Found!" + CRLF;
entityBody = "<HTML>" +
"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
"<BODY>Not Found</BODY></HTML>";
}
// Send the status line.
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
// Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes("File DNE: Content Not Found!");
}
// Close streams and socket.
os.close();
br.close();
socket.close();
}
}
Any help would be greatly appreciated...I feel like it's something simple I'm missing.
I ran your code; it works fine (except for some minor issues with not printing the headers correctly, which every browser I've tried is willing to completely ignore).
Are you sure your working directory is where you expect? Try changing the 404 message to something like:
contentTypeLine = "Content Not Found: " + new File(fileName).getAbsolutePath() + CRLF;
For reference, I ran it with a test harness of:
public static void main(String[] args) throws Exception {
final ServerSocket ss = new ServerSocket(8080);
while (true)
new HttpRequest(ss.accept()).run();
}