依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
新建WebSocketConfig
package com.wu.parker.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author: wusq
* @date: 2018/12/10
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
新建Controller
package com.wu.parker.websocket.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author: wusq
* @date: 2018/12/10
*/
@ServerEndpoint("/websocket/{token}")
@Component
public class WebSocketController {
private static final Logger log = LoggerFactory.getLogger(WebSocketController.class);
public static Map<String, Session> SESSION_MAP = new ConcurrentHashMap<>();
/**
* 连接建立成功调用的方法
* @param session
* @param token
*/
@OnOpen
public void onOpen(Session session, @PathParam("token") String token) {
log.info("{}建立连接", token);
SESSION_MAP.put(token, session);
log.info("建立连接后session数量={}", SESSION_MAP.size());
send(token, "Hello, connection opened!");
}
@OnMessage
public void onMessage(String message, Session session) {
for(Map.Entry<String, Session> entry:SESSION_MAP.entrySet()){
log.info("session.id={}", session.getId());
if(session.getId().equals(entry.getValue().getId())){
log.info("{}发来消息", entry.getKey());
}
break;
}
log.info("接收到消息:{}", message);
}
@OnClose
public void onClose(Session session) {
log.info("有连接关闭");
Map<String, Session> map = new HashMap<>();
SESSION_MAP.forEach((k, v) -> {
if(!session.getId().equals(v.getId())){
map.put(k, v);
}
});
SESSION_MAP = map;
log.info("断开连接后session数量={}", SESSION_MAP.size());
}
void send(String token, String message){
Session session = SESSION_MAP.get(token);
if(session != null){
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("发送信息错误{}", e.getMessage());
e.printStackTrace();
}
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
}
测试页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var socket;
function openSocket() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8080/xxxx/im/25");
//var socketUrl="${request.contextPath}/im/"+$("#userId").val();
var socketUrl="http://localhost:8080/websocket/"+$("#userId").val();
socketUrl=socketUrl.replace("https","ws").replace("http","ws");
console.log(socketUrl)
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function() {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("websocket发生了错误");
}
}
}
function sendMessage() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else {
console.log("您的浏览器支持WebSocket");
console.log('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');
socket.send('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');
}
}
</script>
<body>
<p>【userId】:<div><input id="userId" name="userId" type="text" value="1"></div>
<p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="2"></div>
<p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="这是信息"></div>
<p>【操作】:<div><a onclick="openSocket()">开启socket</a></div>
<p>【操作】:<div><a onclick="sendMessage()">发送消息</a></div>
</body>
</html>
源代码
https://github.com/wu-boy/parker.git
parker-websocket模块