ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java实现WebSocket服务端

2021-10-30 15:01:48  阅读:146  来源: 互联网

标签:java String id key import WebSocket message public 服务端


WebSocket服务端

WebSocket服务端配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * websocket配置类
 * @author daiyg
 * @date 2021/8/24 17:19
 */
@Service
@Configuration
@EnableWebSocket
public class WebSocketConfig {

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

服务端代码

import com.caso.common.core.utils.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author daiyg
 * @date 2021/8/24 18:15
 */
@Component
@ServerEndpoint(value = "/websocket/{id}/{key}", subprotocols = {"protocol"})
public class WebSocketServer {
    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<>();
    private static  ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    private static Logger log = LogManager.getLogger(WebSocketServer.class);
    private String id = "";
    private String key= "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam(value = "id") String id,@PathParam("key") String key, Session session) {

        this.session = session;
        this.id = id;//接收到发送消息的人员编号
        this.key = key;
        if ("1".equals(id)) {
            log.info("非门岗用户连接!");
        } else {
            List<String> ids = new ArrayList<>();
             ids = map.get(id);
            if(StringUtils.isEmpty(ids)){
                ids = new ArrayList<>();
            }
            ids.add(key);
            map.put(id,ids);
            webSocketSet.put(key, this);     //加入set中
        }
        addOnlineCount();           //在线数加1
        log.info("用户" + id + "连接成功!当前在线人数为" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //删除map中值
        List<String> keys = map.get(this.id);
        for (int i = 0; i < keys.size(); i++) {
            if(this.key.equals(keys.get(i))){
                keys.remove(i);
                i--;
            }
        }
        webSocketSet.remove(this.key);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("来自客户端的消息:" + message);

    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void one rror(Session session, Throwable error) {
        log.error("发生错误");
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        error.printStackTrace();

    }

    /**
     * 服务端主动推送消息
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送信息给指定ID用户,如果用户不在线则返回不在线信息给自己
     *
     * @param message
     * @param personKeys
     * @throws IOException
     */
    public static void sendtoUser(String message, String[] personKeys) throws IOException {
        //获取人员集合
        for (String personKey : personKeys) {
            //获取map中对应的链接
            if (map.get(personKey) != null && StringUtils.isNotEmpty(map.get(personKey))) {
                //遍历给连接人发送信息
                for(String s : map.get(personKey)){
                    webSocketSet.get(s).sendMessage(message);
                }
            } else {
                //如果用户不在线则返回不在线信息给自己
                log.error("当前用户不在线:" + personKey);
            }
        }

    }


    /**
     * 发送信息给所有人
     *
     * @param
     * @throws IOException
     */
    public void sendtoAll(String message) throws IOException {
        for (String key : webSocketSet.keySet()) {
            try {
                webSocketSet.get(key).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


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

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}

标签:java,String,id,key,import,WebSocket,message,public,服务端
来源: https://blog.csdn.net/D15306354614/article/details/121050989

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有