1. pom中添加socket支持:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring.version}</version>
</dependency>
2.web.xml文件需要配置参数 async-supported 为 true
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
3.创建对应的处理类, 用来处理消息
public class ChatSocket implements WebSocketHandler {
private static final Logger log = LoggerFactory.getLogger(ChatSocket.class);
private static WebSocketSession socketSession;
private static Core core = Core.getInstance();
private static UserInfo self = new UserInfo(core.getUserSelf());
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
this.socketSession = webSocketSession;
}
@Override
public void handleMessage(
WebSocketSession webSocketSession,
WebSocketMessage<?> webSocketMessage) throws Exception {
Map<String, String> map = JacksonUtils.extractMap(webSocketMessage.getPayload().toString(), new HashMap<>());
String content = map.get("content");
String userName = map.get("userName");
MessageTools.sendMsgById(content, userName);
BaseMsg msg = new BaseMsg("text", content, content, core.getUserName(), userName, self);
sendMsgToUser(msg);
}
@Override
public void handleTransportError(
WebSocketSession webSocketSession,
Throwable throwable) throws Exception {
}
@Override
public void afterConnectionClosed(
WebSocketSession webSocketSession,
CloseStatus closeStatus) throws Exception {
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
4.添加spring-websocket.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">
<!-- websocket处理类 -->
<bean id="myHandler" class="com.wechat.web.socket.ChatSocket"/>
<websocket:handlers>
<websocket:mapping path="/websocket.html" handler="myHandler"/>
</websocket:handlers>
<!-- 注册 sockJS -->
<websocket:handlers>
<websocket:mapping path="/sockjs/websocket.html" handler="myHandler"/>
<websocket:sockjs/>
</websocket:handlers>
</beans>
5.Spring中引入该配置文件
<import resource="spring-websocket.xml"/>
6.前端页面处理
<script src="/res/js/jquery-1.10.2.js"></script>
<script src="/res/js/sockjs.min.js"></script>
$(function () {
var websocket;
// 首先判断是否 支持 WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/websocket.html");
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://localhost:8080/websocket.html");
} else {
websocket = new SockJS("http://localhost:8080/sockjs/websocket.html");
}
// 打开时
websocket.onopen = function (evnt) {
console.log(" websocket.onopen ");
};
// 处理消息时
websocket.onmessage = function (evnt) {
$("#msg").append("<p>(<font color='red'>" + evnt.data + "</font>)</p>");
console.log(" websocket.onmessage ");
};
websocket.onerror = function (evnt) {
console.log(" websocket.onerror ");
};
websocket.onclose = function (evnt) {
console.log(" websocket.onclose ");
};
$("#send_btn").click(function () {
var text = $("#tx").val();
var msg = {
msgContent: text,
postsId: 1
};
websocket.send(JSON.stringify(msg));
});
});
7.配置完成, 调试