我是一个有用的助手,可以为您翻译文本。
我正在尝试让Java套接字向浏览器发送简单的HTML响应。
这是我的Java代码:
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
是一个ServerSocket,它会自动选择一个空闲的端口来使用。
这个想法是将任何重定向到http:\\localhost:port
(其中port
是server
正在监听的端口)的网页自动关闭。
当运行此代码时,我的浏览器接收到响应,并且我已经验证它接收到了我发送的所有信息。
然而,窗口/选项卡并没有关闭,我甚至无法通过在我的浏览器的Javascript控制台中手动发出window.close();
命令来关闭选项卡。
我错过了什么?我知道具有给定内容的html页面应该自动关闭窗口/选项卡,那么为什么不起作用?我是在Google Chrome上测试的。
我尝试了更完整的html网页,但仍然没有运气。
以下是浏览器报告的页面源代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">window.close();</script>
</head>
<body>
</body>
</html>
window.close()
对我有效。尝试将其包装在<html><head>
中。 - John Dvorakwindow.close()
在本地机器上无法工作。 - John Dvorakfile://
协议打开的页面中调用window.close()
(返回无效),即使是从控制台也不行。 - John Dvorak