0

I have a problem that calls for me to Write a simple web server that recognizes only the GET request. When a client connects to your server and sends a command, such as GET filename HTTP/1.0, then return a header
HTTP/1.1 200 OK
followed by a blank line and all lines in the file. If the file doesn't exist, return 404 Not Found instead. You can use String.split() to split the command line.

Here is my code

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * A Server that prints out a file
 * @author 
 *
 */

public class WebServer {

    /**
     * Runs the server.
     */
    public static void main(String[] args) throws IOException {
        final int PORT_NUMBER = 8080;
        ServerSocket server = new ServerSocket(PORT_NUMBER);
        try {
            while (true) {
                Socket socket = server.accept();
                try {
                    PrintWriter out =
                        new PrintWriter(socket.getOutputStream(), true);
                    InputStream instream = socket.getInputStream(); 
                    Scanner a = new Scanner(instream); 
                    String line = a.nextLine();
                    System.out.println(line);

                    //More code here to print out the actual file
                } finally {
                    socket.close();
                }
            }
        }
        finally {
            server.close();
        }
    }
}

The server works as intended as I have already tested its funtionality. What I need some help with is getting String.split() to take into the first four characters(Get followed by a space) and spit out the rest of the file after the command. Its been a while since I have used the String.split() so what would be the best way to getting the program to spit out the file? Any help would be appreciated.

Edited by nyfan68

3
Contributors
2
Replies
3
Views
4 Years
Discussion Span
Last Post by |-|x
0

Have you tried writing a small simple program with a String for testing with the split() method? That would allow you to experiment to see how it works. The Arrays class's toString() method is useful for formatting arrays for printing:
print this: Arrays.toString(<THEARRAYNAMEHERE>)

Try split() with some sample Strings, print the array and see if it is what you want.

0

I think String.split() requires a specified character to 'split' on. If you only need exactly the first four characters, you might be better to do a String.substring(0,3) and String.substring(4) to get the rest of the line.

Edited by |-|x: grammatical error

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.