spring mvc 4中使用websocket
1.spring-servlet.xml中需要配置websocket
<bean id="websocket" class="com.springmvc.utils.MyWebSocketHandler"/>
<websocket:handlers>
<!-配置映射路径->
<websocket:mapping path="/webSocket" handler="websocket"/>
<websocket:handshake-interceptors>
<bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>
2.com.springmvc.utils包中创建MyWebSocketHandler类
package com.springmvc.utils;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
/**
* WebSocket的处理类,用于前端与后台之间的双端通信
*
* @author caixiaocong
*/
public class MyWebSocketHandler extends TextWebSocketHandler implements WebSocketHandler {
private static final Log log = LogFactory.getLog(MyWebSocketHandler.class);
WebSocketSession session;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
this.session = session;
log.info("webSocket connect.");
}
// handle message receive
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
try {
session.sendMessage(new TextMessage("hello"));
} catch (IOException e) {
e.printStackTrace();
}
}
// send message
public void sendMessage() throws IOException{
if(session!=null && session.isOpen()){
session.sendMessage(new TextMessage("hello"));
log.info("webSocket send message");
}
}
}
3.js中使用websocket
$(document).ready(function() {
//webSocke
var hostport = document.location.host;
var socketurl = 'ws://' + hostport + '/Satellite/webSocket';
var ws = new WebSocket(socketurl);
/* ws.onopen = function() {
alert('webSocket connet');
}; */
ws.onmessage = function(event) {
/*这里写websocket中获取到新的消息时候的处理方法*/
};
/* ws.onerror = function() {
alert('webSocket连接失败');
}; */
});