Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7535387
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T06:17:29+00:00 2026-05-30T06:17:29+00:00

I’m running into trouble with this basic, unsophisticated Web Server I wrote in Java.

  • 0

I’m running into trouble with this basic, unsophisticated Web Server I wrote in Java. For some reason, instead of sending the “200 OK” or “404 Not Found” solely to the browser, they’re written onto whatever file is being retrieved. For example, if I try to get an index.html file, I am returned:

example

….rather than the browser trying to compile the HTML.
It’s even worse when trying to get an image, as the file becomes corrupt from the server trying to append the “200 OK” & Content-type to it. Can anyone offer any insight as to how to send the status line & content-type separate from the actual HTML/JPG file? The error goes away entirely when I comment out the “os.writeBytes(statusLine)”, etc, but I still want to send these messages to the browser…just not merged with the file. Any help would be greatly appreciated.

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();
    }
    public static void main(String[] args) throws Exception {
        final ServerSocket ss = new ServerSocket(6789);
        while (true)
            new HttpRequest(ss.accept()).run();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T06:17:30+00:00Added an answer on May 30, 2026 at 6:17 am

    I believe you are missing a CRLF. Isn’t there an extra one needed, at the end of status line

    200 OK
    Content-Type: xxxx

    OF course you could read the HTTP spec, or do a wireshark trace 🙂

    Update: Yes, you have a lot of issues. Read Easy Http for a simple
    summary.

    But anyway you need to say “HTTP/1.0 200 OK” for example

    http://www.somehost.com/path/file.html
    

    first open a socket to the host http://www.somehost.com, port 80 (use the default port of 80 because none is specified in the URL). Then, send something like the following through the socket:

    GET /path/file.html HTTP/1.0
    From: someuser@jmarshall.com
    User-Agent: HTTPTool/1.0
    [blank line here]
    

    The server should respond with something like the following, sent back through the same socket:

    HTTP/1.0 200 OK
    Date: Fri, 31 Dec 1999 23:59:59 GMT
    Content-Type: text/html
    Content-Length: 1354
    
    <html>
    <body>
    <h1>Happy New Millennium!</h1>
    (more file contents)
      .
      .
      .
    </body>
    </html>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I am currently running into a problem where an element is coming back from
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have some data like this: 1 2 3 4 5 9 2 6
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.