说明以tomcat容器为例,tomcat7以上版本开始支持websocket,JFinal集成的jetty服务器不支持websocket
一、包依赖,tomcat7或是javaee包都行,两者二选一,容器中已提供所以只作为提供者
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket-api</artifactId>
<version>7.0.47</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
二、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端请求
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"> <!-- for HTML5 -->
<title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/websocket");
}
else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
打包搞定