關於Spring與WebSocket結合的簡單例子
我的執行環境是:Tomcat 8.0 + Spring 4.0 + Myeclipse2014 + Firefox 42
JDK 1.8 不支援Spring 4.0 之前的版本
使用Google瀏覽器,Spring可能會丟擲異常:The extension [x-webkit-deflate-frame] is not supported] with root cause
使用maven 管理jar包
JAVA程式碼
WebSocket處理類
public class MyHandler extends TextWebSocketHandler implements WebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
System.out.println("-------onMessage-------");
System.out.println(message.toString());
System.out.println(session.getRemoteAddress());
try {
session.sendMessage(new TextMessage("hello")); //傳送訊息給客戶端
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
與客戶端連線
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/myHandler");
}
@Bean
public WebSocketHandler myHandler() {
return new MyHandler();
}
}
JSP程式碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML >
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script type="text/javascript">
var ws = null;
var result = 1;
ws = new WebSocket('ws://127.0.0.1:8082/day_0900_WebSocket/myHandler'); //此處的day_0900_WebSocket專案名,myHandler與WebSocketConfig 裡 的/myHandler對應是建立連線的關鍵。
ws.onopen = function () { //通訊連線成功後執行此程式碼。
result = 2;
};
ws.onmessage = function (event) { //接受服務端訊息時執行此程式碼
alert(event.data);
};
ws.onclose = function (event) { // 連線關閉時執行此程式碼
};
function my(){
if(result == 2){
ws.send("dd"); //向客戶端傳送訊息
}
}
</script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets
rely on Javascript being enabled. Please enable
Javascript and reload this page!</h2></noscript>
<button onclick="my()">hello</button>
</body>
</html>
到此,程式完成,當然不要忘記配置XML檔案(正常配置),這個例子比較簡單,只要環境搭建的沒有問題,參照spring文件,應該沒有什麼問題