java实现WebSocket服务端

java实现WebSocket服务端,第1张

java实现WebSocket服务端

WebSocket服务端
  • 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;


@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;


@Component
@ServerEndpoint(value = "/websocket/{id}/{key}", subprotocols = {"protocol"})
public class WebSocketServer {
    private static int onlineCount = 0;
    private static ConcurrentHashMap webSocketSet = new ConcurrentHashMap<>();
    private static  ConcurrentHashMap> 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 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 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());
    }

    
    @OnMessage
    public void onMessage(String message) {
        log.info("来自客户端的消息:" + message);

    }

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

    }

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

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

    }


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

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4873789.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-11
下一篇 2022-11-11

发表评论

登录后才能评论

评论列表(0条)

保存