Spring Boot笔记-WebSocket的使用

Posted IT1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot笔记-WebSocket的使用相关的知识,希望对你有一定的参考价值。

程序结构如下:

关键源码如下:

WebSocketConfig.java

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();
    }

}

MyController.java

package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.service.WsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    WsService wsService;

    @PostMapping("/msg")
    public Object sendMsg(@RequestBody String req){

        JSONObject jsonObject = JSONObject.parseObject(req);
        System.out.println(jsonObject.getString("msg"));
        wsService.sendInfo(jsonObject.getString("msg"));

        return "success";
    }
}

WsService.java

package com.example.demo.service;

import com.example.demo.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class WsService {

    @Autowired
    public WebSocketServer webSocketServer;

    @Async
    public void sendInfo(String message) {

        webSocketServer.sendInfo(message);
    }
}

WebSocketServer.java

package com.example.demo.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;

@Component
@ServerEndpoint("/ws/{token}")
public class WebSocketServer {

    //每个客户端有一个token
    private String token = "";

    private static HashMap<String, Session> map = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token){

        map.put(token, session);
        this.token = token;
        System.out.println("新连接:" + session);
    }

    @OnClose
    public void onClose(Session session){

        map.remove(this.token);
        System.out.println("连接关闭:" + session);
    }

    @OnError
    public void onError(Session session, Throwable error){

        System.out.println("错误:" + session + "," + error);
    }

    public void onMessage(String message, Session session){

        System.out.println("接收到消息:" + message);
    }

    //群发
    public void sendInfo(String message){

        for (String token : map.keySet()) {
            Session session = map.get(token);
            try {
                session.getBasicRemote().sendText(message);
            }
            catch (IOException e) {

                e.printStackTrace();
            }
        }
    }
}

application.properties

server.port=8880

源码打包下载地址:

https://github.com/fengfanchen/Java/tree/master/WebServiceDemo

 

 

 

以上是关于Spring Boot笔记-WebSocket的使用的主要内容,如果未能解决你的问题,请参考以下文章

在 Spring-boot 中路由 websocket 目标

Spring Boot - WebSocket 握手期间出错

玩转spring boot——websocket

Spring Boot之WebSocket

Spring boot + Websocket

Spring Boot教程32——WebSocket