在springboot中通过jdk原生注解@ServerEndpoint开启ws服务,并无收发消息的逻辑
1.添加pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</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;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Bean
public WebSocketSpringConfigurator webSocketSpringConfigurator(){
return new WebSocketSpringConfigurator();
}
}
3.配置托管给spring管理
package com.example.demo.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import javax.websocket.server.ServerEndpointConfig;
/**
* 以WebSocketConfig.java注册的bean是有WebSocket自己管理的,需要使用配置托管给spring管理
* 否则在@ServerEndpoint下@Autowired无法生效
*/
public class WebSocketSpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
private static volatile BeanFactory context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
WebSocketSpringConfigurator.context = applicationContext;
}
@Override
public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
return context.getBean(clazz);
}
}
3.编写服务端核心类
package com.example.demo.controller;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
@Component
@ServerEndpoint(value = "/webSocket",configurator = WebSocketSpringConfigurator.class)
public class WebSocketController {
private static final Logger log = LoggerFactory.getLogger(WebSocketController.class);
@OnOpen
public void onOpen(Session session) {
log.info("onOpen:" + session.getId());
}
@OnClose
public void onClose(Session session) {
log.info("onClose:" + session.getId());
}
@OnMessage
public void onMessage(Session session, String message) {
log.info("onMessage:" + session.getId());
log.info("onMessage:" + message);
}
@OnError
public void onError(Session session, Throwable throwable) {
log.error("onError:" + session.getId());
log.error("onError:" + throwable.getMessage());
}
}
4.编写客户端核心代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
// 打开一个 web socket
var ws = new WebSocket("ws://127.0.0.1:8040/webSocket");
ws.onopen = function(){
// Web Socket 已连接上,使用 send() 方法发送数据
ws.send("请求open");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("数据已接收...");
};
ws.onclose = function()
{
// 关闭 websocket
alert("连接已关闭...");
};
$(document).ready(function(){
$("#button").click(function(){
ws.send($("#text").val());
console.log($("#text").val())
});
});
</script>
</head>
<body>
<input type="text" id="text">
<button id="button">发送</button>
</body>
</html>
服务端效果如下:
2021-01-12 17:29:02.560 INFO 12723 --- [nio-8082-exec-1] c.e.demo.controller.WebSocketController : onOpen:0
2021-01-12 17:29:02.571 INFO 12723 --- [nio-8082-exec-1] c.e.demo.controller.WebSocketController : onMessage:0
2021-01-12 17:29:02.571 INFO 12723 --- [nio-8082-exec-1] c.e.demo.controller.WebSocketController : onMessage:请求open
2021-01-12 17:29:05.754 INFO 12723 --- [nio-8082-exec-2] c.e.demo.controller.WebSocketController : onMessage:0
2021-01-12 17:29:05.754 INFO 12723 --- [nio-8082-exec-2] c.e.demo.controller.WebSocketController : onMessage:123
客户端效果如下