Spring boot实现原生websocket

网上的大部分教程是基于sockjs,这篇文章内容则是基于原生协议。

后台Spring boot 配置

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {


    @Resource
    private WsSiteHandler wsSiteHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(wsSiteHandler, "site/change").setAllowedOrigins("*");
    }
}
@Component
public class WsSiteHandler  extends TextWebSocketHandler {
    private final static Logger logger = LoggerFactory.getLogger(WsSiteHandler.class);
    private List sessions = new CopyOnWriteArrayList<>();
    private ExecutorService executor = Executors.newCachedThreadPool();


    public void asyncNotice(SiteTo to) {
        executor.execute(() -> {
            String json = new Gson().toJson(to);
            handleTextMessage(null, new TextMessage(json));
        });
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        if (session == null) {
            sessions.removeIf(el -> !el.isOpen());
            sessions.forEach(el -> {
                try {
                    if (el.isOpen()) {
                        el.sendMessage(message);
                    } else {
                        el.close();
                    }
                } catch (IOException e) {
                    logger.error("发送车位信息错误!", message.toString(), e);
                }
            });
        } else {
            try {
                session.sendMessage(message);
            } catch (IOException e) {
                logger.error("发送车位信息错误!", message.toString(), e);
            }
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.add(session);
    }
}

前台调用

initWs () {
   if (!window.WebSocket) return
   this.socket = new WebSocket(`ws://127.0.0.1:9000/marketing/site/change`)
   this.socket.onopen = (event) => {
     console.log('onopen', event)
   }
   this.socket.onmessage = (event) => {
     console.log('onmessage', event.data)
     const siteTo = JSON.parse(event.data)
     siteTo.lock = siteTo.isLock
     const index = this.result.findIndex(el => el.site.id === siteTo.site.id)
     if (index >= 0) {
       this.result.splice(index, 1, siteTo)
     }
   }

   this.socket.onerror = (event) => {
     console.log('onerror', event)
   }
}

你可能感兴趣的:(Spring boot实现原生websocket)