springboot2实现Websocket前后端通信

首先导包:


    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.projectlombok
        lombok
        true
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
    
    
        org.springframework.boot
        spring-boot-starter-websocket
    

接着创建 WebSocketConfig配置类

package com.example.demo.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author xiaochi
 * @date 2022/5/12 9:51
 */
@Configuration
public class WebSocketConfig {

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

继续创建 WebsocketServer 服务

package com.example.demo.websocket.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
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.concurrent.ConcurrentHashMap;

/**
 * @author xiaochi
 * @date 2022/5/12 9:53
 */
@Slf4j
@Component
@ServerEndpoint("/api/ws/{userId}")
public class WebsocketServer{

    private static ConcurrentHashMap resources = new ConcurrentHashMap<>();

    /**
     * 进入链接
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId){
        log.info("【用户"+userId+"加入链接成功】");
        if (resources.containsKey(userId)){
            resources.remove(userId);
            resources.put(userId,session);
            return;
        }
        resources.put(userId,session);
    }

    /**
     * 收到客户端消息并且群发消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        log.info("【收到消息】:{}",message);
        sendMessage(message);
    }

    /**
     * 断开链接
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId){
        log.info("关闭链接:{}",userId);
        resources.remove(userId);
    }

    /**
     * 链接错误
     * @param userId
     * @param error
     */
    @OnError
    public void onError(@PathParam("userId") String userId,Throwable error){
        log.error("【用户"+userId+"链接错误】,{}",error);
    }

    /**
     * 单发消息
     * @param message
     */
    public static void sendMessage(String userId,String message) throws IOException {
        if (resources.containsKey(userId)){
            resources.get(userId).getBasicRemote().sendText(message);
        }
    }

    /**
     * 群发消息
     * @param message
     */
    public static void sendMessage(String message){
        for (Session session : resources.values()){
            try {
                session.getBasicRemote().sendText("群发消息:"+message);
            }catch (Exception e){
                continue;
            }
        }
    }
}

ok,到此完成,接下来就是测试接口实现推送前端消息 WebsocketController

package com.example.demo.websocket.controller;

import com.example.demo.websocket.server.WebsocketServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xiaochi
 * @date 2022/5/12 10:30
 */
@RestController
public class WebsocketController {

    /**
     * 服务端推送消息接口
     * @param msg
     * @return
     */
    @GetMapping("/websocket/{msg}")
    public String sendMessage(@PathVariable String msg){
        WebsocketServer.sendMessage(msg);
        return "ok: "+ msg;
    }
}

前端js




    
    
    
    Document


OK,完成了

你可能感兴趣的:(springboot2实现Websocket前后端通信)