javahtmlsockets

Only part of CSS works when parsed through a socket


Here is what my webpage looks like when I open it normally on my local machine.

Secondly, this is what my webpage looks like after I've sent the HTML and CSS files through a socket, with only part of the styling implemented. For reference, here is how I am loading these files to send to the client:

// accept connection from a client
Socket socket = server.accept();

// if connection is stable, read and write from client
try (OutputStream out = socket.getOutputStream()) {
    InputStream in = socket.getInputStream();
    var line = new BufferedReader(new InputStreamReader(in)).readLine();
    String file = line.substring(5, line.length() - 9);
    if (file.equals("")) {
        file = "index.html";
    } 
    
    // load script file from file directory
    StringBuilder contentBuilder = new StringBuilder();
    try {
        BufferedReader webpage = new BufferedReader(new FileReader(file));
        String str;
        while ((str = webpage.readLine()) != null) {
            contentBuilder.append(str);
        }
        webpage.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String content = contentBuilder.toString();

    // construct valid HTML response message
    final String CRLF = "\r\n"; // 13, 10
    String response = 
        "HTTP/1.1 200 OK" + CRLF + // status line: HTTP_VERSION RESPONSE_CODE RESPONSE_MESSAGE
        "Content-Length: " + content.getBytes().length + CRLF + // header
        CRLF + 
        content + 
        CRLF + CRLF;

    // write HTML message to the client
    out.write(response.getBytes());

Essentially, I read through all the contents of the HTML/CSS file and send it to the socket as a String.

I have printed out the full String objects collected by the BufferedReader and confirmed that the full contents of each file are being read and sent through to the client. Why would the styling only be partially communicated?

EDIT: It may be important to include how I'm using an additional stylesheet online for a font, i.e. I have this in my HTML:

<link rel="stylesheet" href="style.css">        
<link rel="stylesheet" src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

EDIT 2: I tried changing the content length to be content.getBytes(StandardCharsets.UTF_8).length but this unfortunately didn't change anything. I also tried adding CRLF.getBytes(StandardCharsets.UTF_8).length to the content length (as per a suggestion by Steffan) but this didn't work either.


Solution

  • Turns out when reading the CSS file I was reading line by line without adding a \n to the end of each line! So the CSS import was a big mess with certain lines being commented out!