springBoot socket

做个SpringBoot Socket使用的简单记录

功能:后台实时向前台发送提醒信息

 
        
            org.springframework.boot
            spring-boot-starter-websocket
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            net.sf.json-lib
            json-lib
            2.2.3
            jdk15
        

    
@Component
@ServerEndpoint("/msg/{userID}")
public class MsgSocket {

    private static final Logger logger = LoggerFactory.getLogger(MsgSocket.class);
    private static Map clients = new ConcurrentHashMap<>();

    @OnOpen
    public void open(@PathParam("userID")String userID,Session session) {
        clients.put(userID, session);
        logger.info("userID:{},session:{}",userID,session.getAsyncRemote());
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        JSONObject jsonTo = JSONObject.fromObject(message);
        String msg = (String) jsonTo.get("message");
        String userID = (String) jsonTo.get("userID");

        sendMessageTo(msg,userID);

    }

    private void sendMessageTo(String message, String userID) throws IOException {
        Session session = clients.get(userID);

        if (session == null) {
            return;
        }

        session.getAsyncRemote().sendText(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
@RestController
public class TestController {

    @GetMapping("/test")
    public String test() throws IOException {

        MsgSocket msgSocket = new MsgSocket();
        JSONObject jo = new JSONObject();
        jo.put("message", "这是后台返回的消息!");
        jo.put("userID","huang");
        msgSocket.onMessage(jo.toString());

        return "success";
    }
}

用一个简单页面做测试




    
    Title






你可能感兴趣的:(springBoot socket)