SpringBoot整合websocket+测试

pom文件导入websocket依赖

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.45</version>
</dependency>

创建websocket配置文件

package com.minglei.websocketblog.config;

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

/**
 * @Author: 薛定谔的英短
 * @Date: 2020/12/26 10:46
 * @mail: 18612371148@163.com
 */
@Configuration
public class WebSocketConfig {
    /**
     * 这个bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return  new ServerEndpointExporter();
    }
}

创建websocket服务

package com.minglei.websocketblog.server;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: 薛定谔的英短
 * @Date: 2020/12/26 10:46
 * @mail: 18612371148@163.com
 */
@ServerEndpoint("/websocket/{openid}")
@Component
@Slf4j
public class WebSocketServer {
    //静态变量,用来记录当前在线连接数。把它设计成线程安全的。
    private static AtomicInteger onlineCount=new AtomicInteger();

    //用来存放每个客户端对应的WebSocketServer对象
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                log.info("发送数据:{}", message);
                session.getBasicRemote().sendText(message.toString());
            }
        }
    }

    //给指定用户发送信息
    public void sendInfo(String openid, JSONObject message){
        Session session = sessionPools.get(openid);
        log.info("给[{}], session:{}", openid, session);
        try {
            sendMessage(session, message.toJSONString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //给指定用户发送信息
    public void sendInfo(String openid, String message){
        Session session = sessionPools.get(openid);
        log.info("给[{}], session:{}", openid, session);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "openid") String openid){
        sessionPools.put(openid, session);
        addOnlineCount();
        log.info("[{}]加入webSocket,当前人数为:{},session:{}", openid, onlineCount,session);
        try {
//            sendMessage(session, "欢迎[" + openid + "]加入连接!");

        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("人员信息:{}", sessionPools);
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "openid") String openid){
        sessionPools.remove(openid);
        subOnlineCount();
        log.info("[{}]断开webSocket连接,当前人数为:{}", openid, onlineCount);
    }

    /**
     * 收到客户端信息
     */
    @OnMessage
    public void onMessage(String message) throws IOException{
        log.info("客户端[{}]已收到", message);
        message = "客户端:" + message + ",已收到";
        for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        log.error("发生错误:{}", session);
        throwable.printStackTrace();
    }


    /**
     * 人数加1
     */
    public static void addOnlineCount(){
        onlineCount.incrementAndGet();
    }

    /**
     * 人数减1
     */
    public static void subOnlineCount() {
        onlineCount.decrementAndGet();
    }
}

测试是否能连接

websocket在线测试工具
连接的端口:如果你本地8080没被占用就默认8080,如果被占用就在application.yml中改成别的端口。

工具测试结果

websocket服务端执行日志

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值