如何使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 (将#修改为@)