概要

  • 2018年第一天上班
  • WebSocket 简介

  • spring-boot-websocket的使用

前言: 2018年上班第一天,没什么事,就将前些天写的一个关于智能面试机器人项目中使用到的websoket总结如下:

WebSocket 简介

WebSocket是HTML5一种新的协议。它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯,它建立在TCP之上,同HTTP一样通过TCP来传输数据,但是它和HTTP最大不同是:

  • WebSocket 是一种双向通信协议,在建立连接后,WebSocket服务器和Browser/Client Agent都能主动的向对方发送或接收数据,就像Socket一样;
  • WebSocket 需要类似TCP的客户端和服务器端通过握手连接,连接成功后才能相互通信。

spring-boot-websocket的使用

1.maven依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

3.配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
public class MyEndpointConfigure extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
private static BeanFactory context;

@Override
public <T> T getEndpointInstance(Class<T> clazz) {
return context.getBean(clazz);
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
MyEndpointConfigure.context = applicationContext;
}
}
1
2
3
4
5
6
7
8
9
@Configuration
public class WebSocketConfig {

@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}

}

3.核心websocket

特别注意: 不能使用默认的ServerEndpointConfig.Configurator.class,不然会导致服务无法注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@ServerEndpoint(value = "/websocket", configurator = MyEndpointConfigure.class)
@Component
public class WebSocket {

/**
* 成功建立连接调用的方法.
*/
@OnOpen
public void onOpen(Session session) {
}

/**
* 连接关闭调用的方法.
*/
@OnClose
public void onClose(Session session) {
}

/**
* 收到客户端消息后调用的方法.
*/
@OnMessage
public void onMessage(String message, Session session) {
}

/**
* 发生错误时调用.
*/
@OnError
public void onError(Session session, Throwable error) {
}
}