I'm trying to get a Java socket to send a simple HTML response to a browser.
Here's my Java code:
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s;
// this is a test code which just reads in everything the requester sends
while ((s = in.readLine()) != null)
{
System.out.println(s);
if (s.isEmpty())
{
break;
}
}
// send the response to close the tab/window
String response = "<script type=\"text/javascript\">window.close();</script>";
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println("Content-Length: " + response.length());
out.println();
out.println(response);
out.flush();
out.close();
socket.close();
server
is a ServerSocket set to automatically pick an open port to use.
The idea is any webpage redirected to http:\\localhost:port
(where port
is the port server
is listening to) is closed automatically.
When this code gets run, my browser receives the response and I've verified that it receives all the information that I'm sending.
However, the window/tab isn't closing, and I can't even close the tab by manually issuing a window.close();
command into the Javascript console for my browser.
What am I missing here? I know that an html page with the given content should automatically close the window/tab, so why isn't this working? I'm testing this on Google Chrome.
I've tried a more complete html webpage, but still no luck.
Here's what the browser is reporting as the page source:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">window.close();</script>
</head>
<body>
</body>
</html>