Web-服务器推送push——websocket、ajax轮询

Web-服务器推送push

——websocket、ajax轮询

[email protected]

2015年7月31日

 

1  服务器推送websocket:服务端主动向客户端发消息。

目标:客户端和服务器建立长连接,服务端与客户端可实时收发数据。

原理:使用HTTP协议建立全双工的TCP长连接。

方法:HTML5的WebSocket。

参考:http://www.oschina.net/translate/java-ee-html5-websocket-example

1.1 客户端:Websocket类,建立连接,发送数据,接收数据。

目标:建立与服务器的连接,与服务器交互,监听事件,控制连接。

方法:WebSocket类。

1.1.1控制连接:连接服务器、关闭连接

1.1.1.1  连接服务器:创建WebSocket对象时,将直接与服务器进行连接。

      //check support

      var url="ws://localhost:8080/testAMap/ws";

      var ws;

      if ('WebSocket' in window) {  

           ws = new WebSocket(url); //when create a instance, connectto server 

      } else if ('MozWebSocket' in window) {  

           ws = new MozWebSocket(url);  

      } else {  

           alert('WebSocket is not supported by this browser.');  

           return;  

      }  

1.1.1.2  关闭连接:close()。

ws.close();//close by client

1.1.2监听连接事件:连接、接收数据、关闭、出错

1.1.2.1  连接成功事件:onopen()

      ws.onopen=function(evt){

           console.debug("onOpen()");

           ws.send("Hello,this is Client.");//if connected,send message

      };

1.1.2.2  接收数据事件:onmessage()

      ws.onmessage=function(evt){//received message from server

           console.debug("onMessage()");

           console.debug(evt.data);

           ws.close();//close by client

           console.debug("close by client");

      };

1.1.2.3  关闭事件:onclose()

      ws.onclose=function(evt){

           console.debug("onClose()");

      };

1.1.2.4  出错事件:onError()

      ws.onerror=function(evt){

           console.debug("onError()");

      };

1.1.3交互:接收数据、发送数据

1.1.3.1  发送数据:send(msg);

ws.send("Hello,this isClient.");

1.1.3.2  接收数据:onmessage(event);

数据为event.date

参见:接收数据事件:onmessage()

1.1.4示例:连接服务器,并在接收到服务器信息后关闭连接。

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <title>TestWebsocket</title>

</head>

 

<body>

 

Hello World!

<script>

window.onload=function(){

      console.debug("window.onload()");

     

      //web socket

      //check support and connect to server

      var url="ws://localhost:8080/testAMap/ws";

      var ws;

      if ('WebSocket' in window) {  

           ws = new WebSocket(url);

      } else if ('MozWebSocket' in window) {  

           ws = new MozWebSocket(url);  

      } else {  

           alert('WebSocket is not supported by this browser.');  

           return;  

      }  

      ws.onopen=function(evt){

           console.debug("onOpen()");

           ws.send("Hello,this is Client.");//if connected,send message

      };

      ws.onmessage=function(evt){//received message from server

           console.debug("onMessage()");

           console.debug(evt.data);

           ws.close();//close by client

           console.debug("close by client");

      };

      ws.onclose=function(evt){

           console.debug("onClose()");

      };

      ws.onerror=function(evt){

           console.debug("onError()");

      };

};

</script>

</body>

</html>

1.2 服务端:监听连接,发送数据,接收数据。

目标:监听websocket连接,控制连接,主动与客户端交互。

原理:作为hettpservlet监听http请求,处理与websocket有关的请求。

方法:

1.2.1处理websocket的servlet:扩展WebSocketServlet,并实现createWebSocketInbound。

public classWebSocketExtServlet extends WebSocketServlet {

      private static final long serialVersionUID = 1L; 

      @Override

      protectedStreamInbound createWebSocketInbound(String arg0,

                 HttpServletRequest arg1) {

           // TODO Auto-generated method stub

           return new ChatMessage();

      }

}

 

<?xmlversion="1.0" encoding="ISO-8859-1"?>

<web-appxmlns="http://java.sun.com/xml/ns/javaee"

 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

                     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

  version="3.0"

  metadata-complete="true">

 

    <description>

      Servlet and JSP Examples.

    </description>

    <display-name>Servlet and JSPExamples</display-name>

   

    <servlet>

     <servlet-name>ChatWebSocketServlet</servlet-name>

     <servlet-class>com.baiyang.lc.websocketservlet.ChatWebSocketServlet</servlet-class>

    </servlet>

    <servlet-mapping>

       <servlet-name>ChatWebSocketServlet</servlet-name>

       <url-pattern>/chat</url-pattern>

    </servlet-mapping>

   

    <servlet>

     <servlet-name>MyWebSocket</servlet-name>

     <servlet-class>com.test.WebSocketExtServlet</servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>MyWebSocket</servlet-name>

       <url-pattern>/ws</url-pattern>

    </servlet-mapping>

</web-app>

1.2.2主动向客户端发送数据:getWsOutbound().writeTextMessage()

      this.getWsOutbound().writeTextMessage(CharBuffer.wrap("server="+String.valueOf(j))); 

1.2.3监听websocket的状态:onOpen(),onClose(),onTextMessage()

class ChatMessage extendsMessageInbound{

      @Override

      protected void onOpen(WsOutbound outbound) {

           super.onOpen(outbound);

           System.out.println("connet to client.");

      }

     

      @Override

      protected void onClose(int status) {

           System.out.println("onClose()"+status);

           super.onClose(status);

      }

 

      @Override

      protected void onBinaryMessage(ByteBuffer arg0) throwsIOException {

           // TODO Auto-generated method stub

          

      }

 

      @Override

      protected void onTextMessage(CharBuffer arg0) throws IOException{

           // TODO Auto-generated method stub

           this.getWsOutbound().writeTextMessage(CharBuffer.wrap("thisis server..."));

            for (int j = 0; j< 50; j++) { 

                try { 

                   Thread.sleep(1000); 

                   this.getWsOutbound().writeTextMessage(CharBuffer.wrap("server="+String.valueOf(j))); 

                } catch(InterruptedException e) { 

                    // TODOAuto-generated catch block 

                   e.printStackTrace(); 

                } 

            }

      }

     

      private void broadcast(String msg) {}{

           

      }    

}

1.3 示例:服务器定时向客户端发送数据

参考:http://blog.csdn.net/ishallwin/article/details/10299815

客户端:TestWebSocket.htm

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <title>TestWebsocket</title>

</head>

 

<body>

 

Hello World!

<script>

window.onload=function(){

      console.debug("window.onload()");

     

      //web socket

      //check support and connect to server

      var url="ws://localhost:8080/testAMap/ws";

      var ws;

      if ('WebSocket' in window) {  

           ws = new WebSocket(url);

      } else if ('MozWebSocket' in window) {  

           ws = new MozWebSocket(url);  

      } else {  

           alert('WebSocket is not supported by this browser.');  

           return;  

      }  

      ws.onopen=function(evt){

           console.debug("onOpen()");

           ws.send("Hello,this is Client.");//if connected,send message

      };

      ws.onmessage=function(evt){//received message from server

           console.debug("onMessage()");

           console.debug(evt.data);

           //ws.close();//close by client

           //console.debug("close by client");

      };

      ws.onclose=function(evt){

           console.debug("onClose()");

      };

      ws.onerror=function(evt){

           console.debug("onError()");

      };

};

</script>

</body>

</html>

服务器:WebSocketExtServlet.java

package com.test;

 

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

 

importjavax.servlet.http.HttpServletRequest;

 

importorg.apache.catalina.websocket.MessageInbound;

importorg.apache.catalina.websocket.StreamInbound;

importorg.apache.catalina.websocket.WebSocketServlet;

importorg.apache.catalina.websocket.WsOutbound;

 

public classWebSocketExtServlet extends WebSocketServlet {

      private static final long serialVersionUID = 1L; 

      @Override

      protected StreamInbound createWebSocketInbound(String arg0,

                 HttpServletRequest arg1) {

           // TODO Auto-generated method stub

           return new ChatMessage();

      }

     

}

 

class ChatMessage extendsMessageInbound{

      @Override

      protected void onOpen(WsOutbound outbound) {

           super.onOpen(outbound);

           System.out.println("connet to client.");

      }

     

      @Override

      protected void onClose(int status) {

           System.out.println("onClose()"+status);

           super.onClose(status);

      }

 

      @Override

      protected void onBinaryMessage(ByteBuffer arg0) throwsIOException {

           // TODO Auto-generated method stub

          

      }

 

      @Override

      protected void onTextMessage(CharBuffer arg0) throwsIOException {

           // TODO Auto-generated method stub

           this.getWsOutbound().writeTextMessage(CharBuffer.wrap("thisis server..."));

            for (int j = 0; j< 50; j++) { 

                try { 

                    Thread.sleep(1000); 

                   this.getWsOutbound().writeTextMessage(CharBuffer.wrap("server="+String.valueOf(j))); 

                } catch(InterruptedException e) { 

                    // TODOAuto-generated catch block 

                   e.printStackTrace(); 

                } 

            }

      }

     

      private void broadcast(String msg) {}{

          

      }    

}

服务器配置web.xml

<?xmlversion="1.0" encoding="ISO-8859-1"?>

<web-appxmlns="http://java.sun.com/xml/ns/javaee"

 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

                     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

  version="3.0"

  metadata-complete="true">

 

    <description>

      Servlet and JSP Examples.

    </description>

    <display-name>Servlet and JSPExamples</display-name>

 

    <servlet>

     <servlet-name>ChatWebSocketServlet</servlet-name>

     <servlet-class>com.baiyang.lc.websocketservlet.ChatWebSocketServlet</servlet-class>

    </servlet>

    <servlet-mapping>

       <servlet-name>ChatWebSocketServlet</servlet-name>

       <url-pattern>/chat</url-pattern>

    </servlet-mapping>

   

    <servlet>

     <servlet-name>MyWebSocket</servlet-name>

     <servlet-class>com.test.WebSocketExtServlet</servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>MyWebSocket</servlet-name>

       <url-pattern>/ws</url-pattern>

    </servlet-mapping>

</web-app>

2  服务器推送Ajax轮询:服务端使用消息服务器进行消息收发,客户端使用Ajax定时检查消息。

参见:ActiveMQ-Web应用.docx

 

你可能感兴趣的:(Ajax,服务器,websocket,推送,轮询)