前端js
引入websocket
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
//连接WebSocket节点
websocket = new WebSocket("ws://localhost:8080/websocket");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
console.log("websocket发生错误")
};
//连接成功建立的回调方法
websocket.onopen = function(event){
console.log("建立连接");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
console.log("接到消息",event)
}
//连接关闭的回调方法
websocket.onclose = function(){
console.log("连接关闭")
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//发送消息 引入的jquery
$(document).ready(function(){
$("#btn").click(function(){
var msg =$("#text").val();
console.log("建立链接");
websocket.send(msg);
$.get("http://localhost:8080/getWebSocket",{},res=>{
console.log(res);
})
})
});
服务端
配置websocket
package com.zxz.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket支持
* @author zhengkai.blog.csdn.net
*/
@Configuration
public class WebSocketConfig{
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServer
package com.zxz.server;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author zhengkai.blog.csdn.net
*/
@ServerEndpoint(value = "/websocket")
@Component
@Slf4j
public class WebSocketServer {
/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
private static CopyOnWriteArraySet<WebSocketServer> webSocketMap = new CopyOnWriteArraySet<>();
/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
private Session session;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session =session;
webSocketMap.add(this);
log.info("当前在线人数为:"+webSocketMap.size());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
log.info("连接断开");
webSocketMap.remove(this);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("报文:"+message);
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("原因:"+error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
for (WebSocketServer webSocket:webSocketMap) {
webSocket.session.getBasicRemote().sendText(message);
}
}
/**
* 发送自定义消息
* */
public static void sendInfo(String message) throws IOException {
log.info("报文:"+message);
}
}
controller层
package com.zxz.controller;
import com.zxz.server.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class webSocketController {
@Autowired
private WebSocketServer webSocketServer;
@RequestMapping(value = "/getWebSocket",method = RequestMethod.GET)
public String getWebSocket(){
try {
webSocketServer.sendMessage("我主动给你一条消息");
}catch (Exception e){
e.printStackTrace();
}
return "主动推一条消息";
}
}