【发布时间】:2012-11-23 02:46:27
【问题描述】:
我正在尝试使用 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>
【问题讨论】:
-
将
Context-Type更正为Content-Type会发生什么? -
如果
window.close()不能通过控制台工作,服务器不应该受到责备。尝试添加正确的doctype和<html><head>标签。 -
控制台中的
window.close()对我有用。尝试包装<html><head> -
试试 self.close()。另外,我看到了这个帖子:productforums.google.com/forum/#!topic/chrome/GjsCrvPYGlA。我正在使用 IE,但 window.close() 在浏览器中对我不起作用。但是,我尝试了 self.close() 并且成功了。
-
这可能解释 window.close 问题:stackoverflow.com/questions/2032640/…。我改为 并且这有效。