Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Simple Webserver SocketException: socket write error

807580Feb 5 2010 — edited Feb 5 2010
I'm stuck and need some help solving this problem.

When I try to get the 404 message with the webserver, I get this in the output console:
"HttpRequest - java.net.SocketException: Connection reset by peer: socket write error"

I have found the part that makes the problem, but I can't find a solution.


I hope someone can help me with this!
            try
            {
                outputStream.writeBytes(entityBody);
 
            }
import java.io.*;
import java.net.*;
import java.util.*;

public final class WebServer
{
    public static void main(String[] args) throws Exception
    {
        //Port number
        int port = 8080;

        // Establish the listen socket.
        ServerSocket webSocket = new ServerSocket(port);
        
        // Process HTTP service requests in an infinite loop.
        while(true)
        {
            // Listen for a TCP connection request
            Socket tcpSocket = webSocket.accept();

            HttpRequest httpRequest = new HttpRequest(tcpSocket);

            Thread thread = new Thread(httpRequest);

            thread.start();

        }
    }

}
import java.io.*;
import java.net.*;
import java.util.*;

public class HttpRequest implements Runnable
{

    final static String CRLF = "\r\n";
    private Socket socket;
    private String path = "public_html/";

    public HttpRequest(Socket socket)
    {
        this.socket = socket;
    }



    public void run()
    {
        try
        {
            processReguest();
        }
        catch(Exception ex)
        {
            System.err.println(ex);
        }
        
    }

    private void processReguest() throws Exception
    {
        // Get a reference to the socket's input and output streams.
        InputStreamReader inputReader = new InputStreamReader(socket.getInputStream());
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());


        BufferedReader buffReader = new BufferedReader(inputReader);

        String requestLine = buffReader.readLine();

        System.out.println();
        System.out.println(requestLine);

        String headerLine = null;
        while((headerLine = buffReader.readLine()).length() != 0)
        {
            System.out.println(headerLine);
        }

        // Extract the filename from the request line
        StringTokenizer tokens = new StringTokenizer(requestLine);
        tokens.nextToken();
        String fileName = tokens.nextToken();

        //Prepend a "." so that the file request is within the current directory
        fileName = path + "." + fileName;

        //Open the request file
        FileInputStream fileInputStream = null;
        boolean fileExists = true;
        try
        {
            fileInputStream = new FileInputStream(fileName);
            
        }
        catch(FileNotFoundException ex)
        {
            fileExists = false;
        }

        //Construct the response message.
        String statusLine = null;
        String connection = null;
        String contentLength = null;
        String contentTypeLine = null;
        String entityBody = null;
        String contentType = contentType(fileName);
        
        if(!requestLine.startsWith("GET") && !requestLine.startsWith("HEAD"))
        {
            statusLine = "HTTP/1.0 405 Method Not Allowed" + CRLF;
            contentLength = "Content-Length: 0" + CRLF;
            connection = "Connection: close" + CRLF;
            contentTypeLine = "Content-type: " + "text/html" + CRLF;
            entityBody = "<HTML><HEAD><TITLE>405 - Method Not Allowed</TITLE></HEAD><BODY>405 - Method Not Allowed</BODY></HTML>";
            fileInputStream = null;
            fileExists = false;
        }
        else if(fileExists && !contentType.equals("application/octet-stream"))
        {
            statusLine = "HTTP/1.0 200 OK" + CRLF;
            contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
            connection = "Connection: close" + CRLF;
            contentLength = "Content-Length: " + Integer.toString(fileInputStream.available()) + CRLF;

        }
        else if(fileExists && contentType.equals("application/octet-stream"))
        {
            statusLine = "HTTP/1.0 415 Unsupported Media Type" + CRLF;
            contentLength = "Content-Length: 0" + CRLF;
            connection = "Connection: close" + CRLF;
            contentTypeLine = "Content-type: " + "text/html" + CRLF;
            entityBody = "<HTML><HEAD><TITLE>415 - Unsupported Media Type</TITLE></HEAD><BODY>415 - Unsupported Media Type</BODY></HTML>";
            fileInputStream = null;
            fileExists = false;
        }
        else
        {
            statusLine = "HTTP/1.0 404 Bad Request" + CRLF;
            contentLength = "Content-Length: 0" + CRLF;
            connection = "Connection: close" + CRLF;
            contentTypeLine = "Content-type: " + "text/html" + CRLF;
            entityBody = "<HTML><HEAD><TITLE>404 - Not Found</TITLE></HEAD><BODY>404 - Not Found</BODY></HTML>";
        }

        
        // Send the status line
        outputStream.writeBytes(statusLine);
        // Send the connection status
        outputStream.writeBytes(connection);
        // Send the Content-Length
        outputStream.writeBytes(contentLength);
        // Send the content type line
        outputStream.writeBytes(contentTypeLine);
        
        //Send a blank line to indicate the end of the header lines.
        outputStream.writeBytes(CRLF);

        // Send the enity body
        if(fileExists)
        {
            //Den här funkar??
            sendBytes(fileInputStream, outputStream);
            fileInputStream.close();
        }
        else
        {
            try
            {
                outputStream.writeBytes(entityBody);

            }
            catch(SocketException ex)
            {
                System.out.println(ex);
            }
        }


        socket.close();
        inputReader.close();
        outputStream.close();
        buffReader.close();
    }

    private void sendBytes(FileInputStream fileInputStream, DataOutputStream outputStream) throws IOException
    {
        //Construct a 1k buffer to hold bytes on their way to the socket
        byte[] buffer = new byte[1024];
        int bytes = 0;

        // Copy request file inte socket's output stream
        while((bytes = fileInputStream.read(buffer)) != -1)
        {
            outputStream.write(buffer,0, bytes);

        }
    }

    private String contentType(String fileName)
    {
        if(fileName.endsWith(".htm") || fileName.endsWith(".html"))
        {
            return "text/html";
        }
        else if(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg"))
        {
            return "image/jpeg";
        }
        else if(fileName.endsWith(".gif"))
        {
            return "image/gif";
        }
        else if(fileName.endsWith(".png"))
        {
            return "image/png";
        }
        else if(fileName.endsWith(".txt"))
        {
            return "text/plain";
        }
        return "application/octet-stream";
    }

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 5 2010
Added on Feb 5 2010
2 comments
493 views