websocket 在线测试工具: http://coolaf.com/tool/chattest
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 新建 websocket 配置类 WebSocketConfig, 如果不配置,则会出现 websocket 连接异常
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();
}
}
- 新建 websocket 处理类, 请根据自己的业务类型进行处理
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
/**
* 扫图 websocket
* type: 客户端类型
* sn: 客户端标识符
*/
@Component
@ServerEndpoint("/websocketScan")
@Slf4j
public class WebsocketScan {
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session){
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(){
}
/**
* 发生错误时调用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误");
error.printStackTrace();
}
}
- 注:
@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,开发中要多多留意