springboot+webSocket

1.添加依赖

         <!--webSocket-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>

2.创建类:WebSocketConfiguration

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

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

3.创建类:WebsocketServer

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket")
@Component
public class WebsocketServer {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebsocketServer> webSocketSet = new CopyOnWriteArraySet<WebsocketServer>();

    private static ConcurrentHashMap<Session, WebsocketServer> websocketMap = new ConcurrentHashMap<>();

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

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    private Session id;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        this.id = session;
        websocketMap.put(session, this);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        subOnlineCount();           //在线数减1
        webSocketSet.remove(this);  //从set中删除
        websocketMap.remove(session);
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param onlineKey 客户端发送过来的消息唯一Key 系统标识_工号:record_admin
     */
    @OnMessage
    public void onMessage(String onlineKey, Session session) {
        try {
            onLineUserSessionMap.put(onlineKey,session);
            //sendMessageToUser(message, session);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    public void sendMessageToUser(String onlineKey, String message) throws IOException {
        Session session = onLineUserSessionMap.get(onlineKey);
        if(null != session) {
            if (websocketMap.get(session) != null) {
                websocketMap.get(session).sendMessage(message);
            } else {
                //如果用户不在线则返回不在线信息给自己
                System.out.println("当前用户不在线");
            }
        }
    }

    /**
     * 群发消息
     * @param message
     */
    private void sendMessageToAll(String message) {
        for (WebsocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 群发自定义消息
     * */
    private void sendInfo(String message) throws IOException {
        for (WebsocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        WebsocketServer.onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        WebsocketServer.onlineCount--;
    }
}

4.发送:

    @Resource
    private WebsocketServer websocketServer;
    websocketServer.sendMessageToUser(sys + "_" + userName, message);

前端连接:

    var ws = new WebSocket("ws://localhost:8001/websocket");
    ws.onopen = function(){
        ws.send("record_1041");
        console.log("连接...")
    }

    //处理服务器发送来的数据
    ws.onmessage = function(e){
        var msg = e.data;
    }

    ws.onclose = function(){
        console.log("连接关闭");
    }

    ws.onerror = function(){
        console.log('连接失败');
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值