1.引入jar
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.2.9.RELEASE</version>
</dependency>
2.配置
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author duanxiaoqiu
* @Date 2019-06-20 14:54
**/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.使用
package com.example.demo.webSocket;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@ServerEndpoint(value = "/websocket")
@Component // 此注解千万千万不要忘记,它的主要作用就是将这个监听器纳入到Spring容器中进行管理
public class WebSocketServer {
//统计在线人数
private static int onlineCount = 0;
//用本地线程保存session
private static ThreadLocal<Session> sessions = new ThreadLocal<Session>();
//保存所有连接上的session
private static Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
onlineCount++;
}
public static synchronized void subOnlineCount() {
onlineCount--;
}
//连接
@OnOpen
public void onOpen(Session session) {
sessions.set(session);
addOnlineCount();
sessionMap.put(session.getId(), session);
System.out.println("【" + session.getId() + "】连接上服务器======当前在线人数【" + getOnlineCount() + "】");
//连接上后给客户端一个消息
sendMsg(session, "连接服务器成功!");
}
//关闭
@OnClose
public void onClose(Session session) {
subOnlineCount();
sessionMap.remove(session.getId());
System.out.println("【" + session.getId() + "】退出了连接======当前在线人数【" + getOnlineCount() + "】");
}
//接收消息 客户端发送过来的消息
@OnMessage
public void onMessage(String message, Session session) throws InterruptedException {
int i = 0;
int num=1;
while (true) {
for (; i < 3*num; i++) {
for (Session s : sessionMap.values()) {
System.out.println(i);
sendMsg(s, i + "");
Thread.sleep(3000);
}
}
num++;
if (i > 10) {
break;
}
}
//message的格式可以包含sessionid, 格式[SID,内容XXX]:1,内容
/*System.out.println("【" + session.getId() + "】客户端的发送消息======内容【" + message + "】");
String[] split = message.split(",");
String sessionId = split[0];
Session ss = sessionMap.get(sessionId);
if (ss != null) {
String msgTo = "【" + session.getId() + "】发送给【您】的消息: 【" + split[1] + "】";
String msgMe = "【我】发送消息给【" + ss.getId() + "】: " + split[1];
sendMsg(ss, msgTo);
sendMsg(session, msgMe);
} else {
for (Session s : sessionMap.values()) {
if (!s.getId().equals(session.getId())) {
sendMsg(s, "【" + session.getId() + "】发送给【您】的广播消息: 【" + message + "】");
} else {
sendMsg(session, "【我】发送广播消息给大家 " + message);
}
}
}*/
/*String sid = session.getId();
Session ss = sessionMap.get(sid);*/
}
//异常
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("发生异常!");
throwable.printStackTrace();
}
//统一的发送消息方法
public synchronized void sendMsg(Session session, String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.页面
package com.example.demo.controller;
/**
* @author duanxiaoqiu
* @Date 2019-06-14 15:05
**/
import com.example.demo.dao.StudentDao;
import com.example.demo.model.StudentEbo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Slf4j
@Controller
@RequestMapping("/")
public class TestController {
@Autowired
private StudentDao studentDao;
@Autowired
private CacheManager cacheManager;
@RequestMapping("/")
@ResponseBody
public String index() {
return studentDao.getStuById(1L).getName();
}
@RequestMapping("/websocket")
public String init() {
return "index.html";
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My WebSocket Test</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/websocket");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>