如何解决如何使Java Web Server不断向HTML网页发送响应?
下面是一个示例代码段,当用户在浏览器中访问127.0.0.1:8080时,该代码段将以Java生成Web服务器并在浏览器中显示Hello World。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.socket;
public class SimpleWebServer {
Socket remote;
ServerSocket s;
/**
* WebServer constructor.
* @throws java.io.IOException
*/
protected void start() throws IOException {
try {
s = new ServerSocket(8080);
System.out.println("Webserver starting up on port 8080");
System.out.println("(press ctrl-c to exit)");
} catch (IOException e) {
System.out.println("Error: " + e);
return;
}
for (;;) {
try {
remote = s.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
PrintWriter out = new PrintWriter(remote.getoutputStream());
String str = ".";
while (!str.equals("")) {
str = in.readLine();
}
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("Server: Bot");
// this blank line signals the end of the headers
out.println("");
// Send the HTML page
out.println("Hello World");
out.flush();
remote.close();
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
}
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
SimpleWebServer ws = new SimpleWebServer();
ws.start();
}
}
是否可以让服务器在不让用户不断刷新页面的情况下继续向浏览器发送响应?可以说继续显示递增的数字(不在页面上附加数据)。
我不是在寻找WebSocket解决方案,而是Java中的Web服务器。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。