说明以tomcat容器为例,tomcat7以上版本开始支持websocket,JFinal集成的jetty服务器不支持websocket
一、包依赖,tomcat7或是javaee包都行,两者二选一,容器中已提供所以只作为提供者
org.apache.tomcat tomcat-websocket-api 7.0.47 provided javax javaee-api 7.0 provided
二、JFinal的配置,需要一个Handler拦截websocket请求,WebSocketHandler实现如下
package com.nmtx.manager.handler;import java.util.regex.Pattern;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.jfinal.handler.Handler;import com.jfinal.kit.StrKit;public class WebSocketHandler extends Handler{ private Pattern filterUrlRegxPattern; public WebSocketHandler(String filterUrlRegx) { if (StrKit.isBlank(filterUrlRegx)) throw new IllegalArgumentException("The para filterUrlRegx can not be blank."); filterUrlRegxPattern = Pattern.compile(filterUrlRegx); } @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { if (filterUrlRegxPattern.matcher(target).find()) return ; else next.handle(target, request, response, isHandled); }}
JFinalConfig中配置
/** * 接收处理跳转 */ @Override public void configHandler(Handlers me) { me.add(new WebSocketHandler("^/websocket")); }
配置WebSocket处理类
package com.nmtx.manager.controller.websocket;import java.io.IOException;import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;import com.jfinal.kit.JsonKit;import com.jfinal.plugin.redis.Redis;import com.nmtx.common.ErrorCode;import com.nmtx.common.MessageResp;import com.nmtx.manager.common.base.LoggerManager;import com.nmtx.manager.model.message.Message;import com.nmtx.manager.model.permission.User;import com.nmtx.manager.utils.WebSocketSessionUtils;import com.nmtx.plugins.auth.AuthUser;import com.nmtx.utils.ModelUtils;@ServerEndpoint("/websocket")public class WebSocketController { @OnOpen public void onOpen(Session session) { } @OnClose public void onClose(Session session) { } @OnMessage public void onMessage(String requestJson, Session session) { session.getBasicRemote().sendText(requestJson); }}
三,html5端请求
Java后端WebSocket的Tomcat实现 Welcome
打包搞定