一、Spring集成WebSocket
1.1、maven导包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
1.2、建包扫描
创建websocket包并扫描
<context:component-scan base-package="cn.ykf.websocket" />
1.3、创建消息处理类
//消息处理类
public class MyHandler extends TextWebSocketHandler {
// 在线用户列表
public static final Map<String, WebSocketSession> userSocketSessionMap = new HashMap<String, WebSocketSession>();
// 用户连接成功 就被调用
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.err.println("用户连接成功");
userSocketSessionMap.put(session.getId(),session);
}
// 消息处理方法
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
try {
//session.sendMessage(message);//发送给当前人
sendMessagesToUsers(message);//给所有的用户发送消息
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 给所有的用户发送消息
*/
public void sendMessagesToUsers(TextMessage message){
for(Map.Entry<String, WebSocketSession> item : userSocketSessionMap.entrySet()){
WebSocketSession user=item.getValue();
try {
//isOpen()在线就发送
if(user.isOpen()){
user.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//用户退出后的处理,退出之后,要将用户信息从websocket的session中remove掉,这样用户就处于离线状态了,也不会占用系统资源
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
try {
if(session.isOpen()){
session.close();
}
userSocketSessionMap.remove(session.getId());
System.out.println("退出系统");
}catch (Exception e){
System.out.println("用户非正常关闭");
}
}
}
1.4、webSocket配置类
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/myHandler");
}
@Bean
public WebSocketHandler myHandler() {
return new MyHandler();
}
}
二、页面测试(聊天室案例)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<script src="/lib/layui/layui.js"></script>
<body>
<div style="margin-left: 10px">
<h1>聊天室</h1>
<textarea id="txtArea" rows="10" cols="100">
</textarea>
<br />
<input id="txtInput" type="text" /> <button id="sendBtn">发送消息</button>
</div>
<script type="text/javascript">
$(function(){
$('#sendBtn').click(function(){
var txtInput=$("#txtInput").val();
// var id = ${session.loginUser.id};
//alert(id)
websocket.send(txtInput+"|"+"\r\n");
})
})
var websocket;
function connect() {
//js连接websocket
websocket = new WebSocket("ws://localhost:80/myHandler");
// 连接成功
websocket.onopen = function(evnt) {
console.log(" websocket.onopen ");
var msg={"name":"kd"};
// 发送消息
//websocket.send(JSON.stringify(msg));
};
// 接受消息
websocket.onmessage = function (event) {
console.log('Received: ' + event.data);
var text= $("#txtArea").val();
$("#txtArea").val(text+event.data)
};
// 连接关闭
websocket.onclose = function (event) {
console.log('Info: connection closed.');
};
//当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
websocket.close();
}
}
connect();
</script>
</body>
</html>
- 这篇文章主要简单讲解websocket的基本使用,那么在接下来的下篇文章博主会更新如何使用layim连接websocket实现即时通讯功能