1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.新建WebSocket配置类
@Configuration
public class WebsocketConfiguration {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.新建WebSocket服务端
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* WebSocket服务端
* @author jspanjsp
*
*/
//你的WebSocket访问地址
@ServerEndpoint("/webSocket")
@Component
public class MyWebsocketServer {
/**
* 存放所有在线的客户端
*/
private static Map<String, Session> clients = new ConcurrentHashMap<>();
private static final Logger log = LoggerFactory.getLogger(MyWebsocketServer.class);
@OnOpen
public void onOpen(Session session) {
log.info("有新的客户端连接了: {}", session.getId());
//将新用户存入在线的组
clients.put(session.getId(), session);
}
/**
* 客户端关闭
* @param session session
*/
@OnClose
public void onClose(Session session) {
log.info("有用户断开了, id为:{}", session.getId());
//将掉线的用户移除在线的组里
clients.remove(session.getId());
}
/**
* 发生错误
* @param throwable e
*/
@OnError
public void onError(Throwable throwable) {
throwable.printStackTrace();
}
/**
* 收到客户端发来消息
* @param message 消息对象
*/
@OnMessage
public void onMessage(String message) {
log.info("服务端收到客户端发来的消息: {}", message);
this.sendAll(message);
}
/**
* 群发消息
* @param message 消息内容
*/
private void sendAll(String message) {
for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
sessionEntry.getValue().getAsyncRemote().sendText(message);
}
}
}
4. 启动后,客户端连接websocket
$(function(){
var websocket = null;
//浏览器是否支持
if ('WebSocket' in window) {
// 上面我们给webSocket定位的路径(MyWebsocketServer.java配置的@ServerEndpoint)
websocket = new WebSocket('ws://localhost:80/webSocket');
} else {
alert('该浏览器不支持websocket!');
}
//建立连接
websocket.onopen = function (event) {
console.log('建立连接');
//给服务端发送消息
websocket.send("客户端发送消息");
}
//关闭连接
websocket.onclose = function (event) {
console.log('连接关闭');
}
//消息来的时候的事件
websocket.onmessage = function (event) {
// 这里event.data就是我们从后台推送过来的消息
console.log('收到消息:' + event.data);
// 在这里我们可以在页面中放置一个音乐,例如“您有新的订单了!”这样的提示音
document.getElementById("newOrderMp3").play();
}
//发生错误时
websocket.onerror = function () {
alert('websocket通信发生错误!');
}
//窗口关闭时,Websocket关闭
window.onbeforeunload = function () {
websocket.close();
}
});
5. 客户端发送消息得到的响应和服务端的响应