Hoko L
Hoko L

Reputation: 97

Trouble writing to OutputStream socket

I am writing a simple web server program for class that sends files to the web browser on request. I have written as much as I could. The difficulty is getting the data written to the OutputStream. I don't know what I am missing. I couldn't get the simple request to show up on the web browser.

I wrote it to the "name" OutputStream but when I reload the tab in the browser with the URL: "http://localhost:50505/path/file.txt" or any other like that "localhost:50505" it doesn't show up what I wrote to the OutputStream "name". It is supposed to show that.

package lab11;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;

public class main {
    private static final int LISTENING_PORT = 50505;

    public static void main(String[] args) {
        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(LISTENING_PORT);
        }
        catch (Exception e) {
            System.out.println("Failed to create listening socket.");
            return;
        }
        System.out.println("Listening on port " + LISTENING_PORT);
        try {
            while (true) {
                Socket connection = serverSocket.accept();
                System.out.println("\nConnection from "
                        + connection.getRemoteSocketAddress());
                handleConnection(connection);
            }
        }
        catch (Exception e) {
            System.out.println("Server socket shut down unexpectedly!");
            System.out.println("Error: " + e);
            System.out.println("Exiting.");
        }
    }
    
    public static void handleConnection(Socket sok) {
        try {
//          Scanner in = new Scanner(sok.getInputStream());
            InputStream one = sok.getInputStream();
            InputStreamReader isr = new InputStreamReader(one);
            BufferedReader br = new BufferedReader(isr);
            String rootDirectory = "/files";
            String pathToFile;
//          File file = new File(rootDirectory + pathToFile);
            StringBuilder request = new StringBuilder();
            String line;
            line = br.readLine();
            while (!line.isEmpty()) {
                request.append(line + "\r\n");
                line = br.readLine();
            }
//          System.out.print(request);
            String[] splitline = request.toString().split("\n");
            String get = null;
            String file = null;
            for (String i : splitline) {
                if (i.contains("GET")) {
                    
                    get = i;
                    String[] splitget = get.split(" ");
                    file = splitget[1];
                }
            }
            }
            OutputStream name = sok.getOutputStream();
            Boolean doesexist = thefile.exists();
            if (doesexist.equals(true)) {
                
                PrintWriter response = new PrintWriter(System.out);
                response.write("HTTP/1.1 200 OK\r\n");
                response.write("Connection: close\r\n");
                response.write("Content-Length: " + thefile.length() + "\r\n");
                response.flush();
                response.close();
                
                sendFile(thefile, name);

            } else {
                System.out.print(thefile.exists() + "\n" + thefile.isDirectory() + "\n" + thefile.canRead());
            }

            
        }
        catch (Exception e) {
            System.out.println("Error while communicating with client: " + e);
        }
        finally {  // make SURE connection is closed before returning!
            try {
                sok.close();
            }
            catch (Exception e) {
            }
            System.out.println("Connection closed.");
        }
    }
    

    
    private static void sendFile(File file, OutputStream socketOut) throws
      IOException {
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        OutputStream out = new BufferedOutputStream(socketOut);
        while (true) {
          int x = in.read(); // read one byte from file
          if (x < 0)
             break; // end of file reached
          out.write(x);  // write the byte to the socket
       }
       out.flush();
    }
}

So, I don't know what I really did wrong.

When I load the browser with localhost:50505 it just says can't connect or localhost refused to connect.

Upvotes: 0

Views: 107

Answers (1)

Pentracchiano
Pentracchiano

Reputation: 188

You are writing the HTTP response in System.out. You should write it in name, after the headers, in the body of the response. You probably want to describe it with a Content-Type header to make the receiver correctly show the file.

Upvotes: 1

Related Questions