1漏设、先建立一個Maven項目,如果是老項目,也可轉(zhuǎn)成maven項目酬诀,參見我之前寫的一篇幫助:
Myeclipse普通java項目轉(zhuǎn)maven項目
2、pom.xml引用相關(guān)jar包骆撇,1.7之后支持料滥,配置如下:
<dependencies>
<!-- <dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency> -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
tomcat7和jave EE 1.7都支持,注意引用一個艾船,不要重復(fù)。
3高每、編寫事件攔截處理代碼:
ZhiWebSocketHandler.java
package com.yyxz.main;
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 ZhiWebSocketHandler extends Handler {
private Pattern filterUrlRegxPattern;
public ZhiWebSocketHandler(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) {
// TODO Auto-generated method stub
if (filterUrlRegxPattern.matcher(target).find())
return ;
else {
next.handle(target, request, response, isHandled);
}
}
}
在JFinal Config中進(jìn)行注冊:
public class DemoConfig extends JFinalConfig {
//...
public void configHandler(Handlers me) {
me.add(new ContextPathHandler("ctx"));
me.add(new ZhiWebSocketHandler("^/websocket"));
// 也可以使用UrlSkipHandler屿岂,就不用編寫Handler處理類了
// me.add(new UrlSkipHandler("^/websocket", false));
}
//...
}
4、后臺監(jiān)聽websocket代碼:
WebSocketController.java
package com.yyxz.controller;
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;
@ServerEndpoint("/websocket")
public class WebSocketController {
public WebSocketController() {
System.out.println(" WebSocket init~~~");
}
@OnOpen
public void onOpen(Session session) {
System.out.println("onOpen");
}
@OnClose
public void onClose(Session session) {
System.out.println("onClose");
}
// @OnError
// public void onError(Session session) {
// System.out.println("onError");
// }
@OnMessage
public void onMessage(String requestJson, Session session)
throws IOException {
requestJson = "一一小知回復(fù):" + requestJson;
System.out.println(requestJson);
session.getBasicRemote().sendText(requestJson);
}
}
5鲸匿、在前端發(fā)起爷怀,編寫頁面:
webSocketTest.jsp
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- for HTML5 -->
<title>Java后端WebSocket的Tomcat實現(xiàn)</title>
</head>
<body>
Welcome
<br />
<input id="text" type="text" />
<button onclick="send()">發(fā)送消息</button>
<hr />
<button onclick="closeWebSocket()">關(guān)閉WebSocket連接</button>
<hr />
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判斷當(dāng)前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/yiyixiaozhi/websocket");
}
else {
alert('當(dāng)前瀏覽器 Not support websocket')
}
//連接發(fā)生錯誤的回調(diào)方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket連接發(fā)生錯誤");
};
//連接成功建立的回調(diào)方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket連接成功");
}
//接收到消息的回調(diào)方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//連接關(guān)閉的回調(diào)方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket連接關(guān)閉");
}
//監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時带欢,主動去關(guān)閉websocket連接运授,防止連接還沒斷開就關(guān)閉窗口,server端會拋異常乔煞。
window.onbeforeunload = function () {
closeWebSocket();
}
//將消息顯示在網(wǎng)頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關(guān)閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
//發(fā)送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
結(jié)果如下: