<!--websocket pom -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
#Configuration
@Configuration
@EnableWebSocket
public class WebsockConfig implements WebSocketConfigurer {
@Bean
public CurrpricewebsockedHandle currpeicehandler(){
CurrpricewebsockedHandle handle = new CurrpricewebsockedHandle();
return handle;
}
@Bean
public WebSocketInterceptory interceptory(){
WebSocketInterceptory interceptory = new WebSocketInterceptory();
return interceptory;
}
//注册websocket处理器
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// 配置ws处理器/ws握手拦截器
//path交给handle处理而不是 实现业务逻辑 可以理解为任务的收集分发中心
registry.addHandler(currpeicehandler(),"updatecurrentprice").addInterceptors(interceptory()).setAllowedOrigins("*");
}
}
<!--handler-->
public class CurrpricewebsockedHandle extends TextWebSocketHandler {
Map<String, WebSocketSession> map = new ConcurrentSkipListMap<String, WebSocketSession>();
//建立连接
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
map.put(session.getId(), session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
//接受到前端的消息
String payload = message.getPayload().toString();
for (Map.Entry<String, WebSocketSession> m : map.entrySet()){
String pay = JSON.toJSONString(payload);
TextMessage textMessage = new TextMessage(pay);
try {
m.getValue().sendMessage(textMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
}
}
<!--Interceptor-->
public class WebSocketInterceptory implements HandshakeInterceptor {
// beforeHandshake,在调用handler前处理方法。常用在注册用户信息,
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}
前端代码
//ws协议
var currUrl = "ws://"+location.host+"/updatecurrentprice"
var currws = new WebSocket(currUrl);
function bid() {
//触发修改数据库
$.post("/moon/Commodity/updateCurrPrice",{
commid : $("#commids").text(),
addmoney :$(".join-money").val()
},function(data){
// 接受后端返回过来的消息
currws.send(p)
});