websocket实现MessageInbound类 onTextMessage()/onBinaryMessage()方法负责信息的推送,canvas负责绘画,看代码自己研究比较好,源码在后面
demo的服务器:tomcat 7.0.47,
浏览器为支持websocket version 13版本,
注意:引入jar包在tomcat的lib目录下:catalina.jar tomcat-coyote.jar,发布项目后需要删掉,否则包冲突!每个浏览器的websocket版本不同 需要不断测试 慎用!!!
先创建一个服务初始化类 SocketService ,一个servlet
package com.websocket; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.apache.catalina.websocket.MessageInbound; public class SocketService extends HttpServlet { private static ListsocketList; public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub SocketService.socketList = new ArrayList (); super.init(config); } public static List getMessageInbound() { return SocketService.socketList; } }
再创建WebSocketImp,实现WebSocketServlet类
package com.websocket; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WebSocketServlet; public class WebSocketImp extends WebSocketServlet{ protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest arg1) { // TODO Auto-generated method stub return new WebSocketInboundImp(); } }
然后是MessageInbound 的实现类
package com.websocket; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import org.apache.catalina.websocket.MessageInbound; import org.apache.catalina.websocket.WsOutbound; public class WebSocketInboundImp extends MessageInbound { /** * 打开 */ protected void onOpen(WsOutbound outbound) { // TODO Auto-generated method stub SocketService.getMessageInbound().add(this); super.onOpen(outbound); } /** * 关闭 */ protected void onClose(int status) { // TODO Auto-generated method stub SocketService.getMessageInbound().remove(this); super.onClose(status); } /** * 流处理 */ protected void onBinaryMessage(ByteBuffer arg0) throws IOException { // TODO Auto-generated method stub for (MessageInbound bmsg : SocketService.getMessageInbound()) { ByteBuffer bb = ByteBuffer.wrap(arg0.array()); WsOutbound wb = bmsg.getWsOutbound(); wb.writeBinaryMessage(bb); wb.flush(); } } /** * 字符处理 */ protected void onTextMessage(CharBuffer arg0) throws IOException { // TODO Auto-generated method stub for (MessageInbound msgib : SocketService.getMessageInbound()) { CharBuffer cb = CharBuffer.wrap(arg0); WsOutbound wb = msgib.getWsOutbound(); wb.writeTextMessage(cb); wb.flush(); } } }
接着看web.xml
SocketService com.websocket.WebSocketImp SocketService /web sload com.websocket.SocketService 1 index.jsp
最后是界面,比较丑,
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>My JSP 'index.jsp' starting page testing...
一个效果图:多个不同的浏览器发信息,实现同步推送