Reputation: 197
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");
}
}
}
Upvotes: 1
Views: 203
Reputation: 1823
Be aware that
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();
Upvotes: 0
Reputation: 1054
You have to close the OutputStream:
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");
outToClient.close();
}
Upvotes: 1