spring boot中使用webSocket
文章目录
- spring boot中使用webSocket
- 引入依赖
- 支持
- 配置类
- 接口类
- 前端连接方式
- 前端信息发送方式
引入依赖
需要在基础的spring boot web项目项目中添加下面一个依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
支持
在spring boot启动类上加上@EnableWebSocket注解,如下:
@SpringBootApplication
@EnableWebSocket
public class FriendApplication {
public static void main(String[] args) {
SpringApplication.run(FriendApplication.class, args);
}
}
配置类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
接口类
@CrossOrigin
@ServerEndpoint("/chat/{sender}/{receiver}")
@Component
public class ChatSocketServer {
@OnOpen
public void onOpen(Session session){}
@OnClose
public void onClose( Session session){
System.out.println("close-------");
sessionMap.remove(session);
}
@OnError
public void onError(Throwable throwable) {
throwable.printStackTrace();
}
@OnMessage
public void onMessage(Session session,String message){}
}
前端连接方式
var url = `ws://localhost:8080/chat/${uId}/${revicer}`;
webSocket = new WebSocket(url);
webSocket.onopen = function () {
console.log('webSocket连接创建。。。');
}
webSocket.onclose = function () {
console.log("close")
}
webSocket.onmessage = function (event) {
console.log(event.data)
const obj = JSON.parse(event.data);
}
webSocket.onerror = function (event) {
console.log('webSocket连接异常。。。');
}
前端信息发送方式
$('#sendBtn').click(function () {
var msg = $('#sendMessage').val();
webSocket.send(msg);
$('#sendMessage').val('');
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)