• Long-Polling, Websockets, SSE(Server-Sent Event), WebRTC 之间的区别与使用


    1、首先看下最简单的SSE:

    只用支持SSE的浏览器(大部分)即可,浏览器内置EventSource对象,该对象默认隔三秒刷新一下response的数据。

    HTML代码(取自w3cschool):

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    <h1>获取服务端更新数据</h1>
    <div id="result"></div>
    
    <script>
    if(typeof(EventSource)!=="undefined")
      {var source=new EventSource("socket");//参数为请求链接
      source.onmessage=function(event)
        {
            document.getElementById("result").innerHTML+=event.data + "<br>";
        };
      }
    else
      {
      document.getElementById("result").innerHTML="抱歉,你的浏览器不支持 server-sent 事件...";
      }
    </script>
    
    </body>
    </html>

    Tomcat服务端代码:

    public class TestServlet extends HttpServlet{protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
            res.setHeader("Content-Type", "text/event-stream;charset=UTF-8"); //也可以直接设置Content-Type,但是编码一定要一致
            PrintWriter p = res.getWriter();
            while(true) {
                Thread.sleep(1000);
                p.print("data:");//一定要以data:开头,否则取不到数据
                p.println("abc");
                p.println();//一定要跟空行,否则无数据,不触发onmessage。
                p.flush();
            }
        }
        
    }

    这样就可以了,具体的可以查看EventSource详细内容

  • 相关阅读:
    命令[34]
    命令[33]
    命令[27]
    命令[38]
    命令[19]
    命令[22]
    命令[30]
    命令[37]
    命令[23]
    命令[26]
  • 原文地址:https://www.cnblogs.com/guangshan/p/4453731.html
Copyright © 2020-2023  润新知