Web-服务器推送push
——websocket、ajax轮询
2015年7月31日
目标:客户端和服务器建立长连接,服务端与客户端可实时收发数据。
原理:使用HTTP协议建立全双工的TCP长连接。
方法:HTML5的WebSocket。
参考:http://www.oschina.net/translate/java-ee-html5-websocket-example
目标:建立与服务器的连接,与服务器交互,监听事件,控制连接。
方法: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;
}
ws.close();//close by client
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()");
};
ws.send("Hello,this isClient.");
数据为event.date
参见:接收数据事件:onmessage()
<!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>
目标:监听websocket连接,控制连接,主动与客户端交互。
原理:作为hettpservlet监听http请求,处理与websocket有关的请求。
方法:
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>
this.getWsOutbound().writeTextMessage(CharBuffer.wrap("server="+String.valueOf(j)));
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) {}{
}
}
参考: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>
参见:ActiveMQ-Web应用.docx