Search code examples
javahttpserversocket

Cannot get response from java server app


I have the following code below which is a very basic server. In the browser I put something like: localhost:6789/xxxx. When the app is running it does read the request from the client but then the message "This site can’t be reached" is displayed and the app throws an exception. What is the best way to respond to the client?

import java.net.*;
import java.io.*;
import java.net.Socket;

public class URLConnection {
    public static void main(String[] args)throws IOException {
        String clientSentence;
        ServerSocket welcomeSocket = new ServerSocket(6789);

        while (true) {
         Socket connectionSocket = welcomeSocket.accept();
         BufferedReader inFromClient =
          new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
         DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
         clientSentence = inFromClient.readLine();
         System.out.println("Received: " + clientSentence);
         outToClient.writeBytes("HTTP/1.1 200 OK");
        }
    }

}

Solution

  • Be aware that

    • the request may not necessarily be HTTP 1.1, and thus your response would be invalid.
    • there will actually be several clientSentence (i.e. consider adding a loop as below)

      while (true) {
          Socket connectionSocket = welcomeSocket.accept();
          BufferedReader inFromClient =
                  new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
          DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
      
          while(true) {
              clientSentence = inFromClient.readLine();
              if (clientSentence != null && clientSentence.trim().isEmpty()) {
                  break;
              } else {
                  System.out.println("Received: " + clientSentence);
              }
          }
      
          outToClient.writeBytes("HTTP/1.1 200 OK\n\nHello world");
          outToClient.close();