3.WebSocketServer及其它代码

WebSocketServer配置

@Slf4j
@ServerEndpoint(value = "/server/{userId}")
@Component
public class WebSocketServer {

    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

        try {
            sendMessage("用户".concat(userId)+"连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

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

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:"+userId);
        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage("测试消息推送到前端");
        }else{
            log.error("用户"+userId+",不在线!");
        }
    }

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

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

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

controller

@RestController
@RequestMapping("websocket")
public class WebSocketController {

    @RequestMapping("/push/{toUserId}")
    public ResponseEntity<String> pushToWeb( @PathVariable String toUserId) throws IOException {
        String str ="消息测试推送至前端";
        WebSocketServer.sendInfo(str,toUserId);
        Map map = new HashMap();
        map.put("message",str);
        return ResponseEntity.ok(JSON.toJSONString(map));
    }
}

pom依赖

    <dependencies>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.0.RELEASE</version>
        </dependency>

        <!--日志-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
            <version>2.3.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.8.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.44</version>
        </dependency>
    </dependencies>

启动项

@Slf4j
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class WebsocketApplication {

    public static void main(String[] args) {
        // 设置开始时间
        long startTime = System.currentTimeMillis();
        ApplicationContext context = SpringApplication.run(WebsocketApplication.class, args);
        // 设置结束时间
        long endTime = System.currentTimeMillis();
        log.info("\n                            _ooOoo_  \n" +
                "                           o8888888o  \n" +
                "                           88\" . \"88  \n" +
                "                           (| -_- |)  \n" +
                "                            O\\ = /O  \n" +
                "                        ____/`---'\\____  \n" +
                "                        .   ' \\\\| |// `.  \n" +
                "                       / \\\\||| : |||// \\  \n" +
                "                     / _||||| -:- |||||- \\  \n" +
                "                       | | \\\\\\ - /// | |  \n" +
                "                     | \\_| ''\\---/'' | |  \n" +
                "                      \\ .-\\__ `-` ___/-. /  \n" +
                "                   ___`. .' /--.--\\ `. . __  \n" +
                "                .\"\" '< `.___\\_<|>_/___.' >'\"\".  \n" +
                "               | | : `- \\`.;`\\ _ /`;.`/ - ` : | |  \n" +
                "                 \\ \\ `-. \\_ __\\ /__ _/ .-` / /  \n" +
                "         ======`-.____`-.___\\_____/___.-`____.-'======  \n" +
                "                            `=---='  \n" +
                "  \n" +
                "         .............................................  \n" +
                "          启动成功  佛祖保佑  代码永无BUG 需求永不变更");
        log.info(
                "Application {} 启动成功, 应用端口 {}, 耗时 {} 秒, 加载 Spring 组件 {} 个.\nApplication Path: {}.\nApplication Version: {}.",
                WebsocketApplication.class.getName(),
                context.getEnvironment().getProperty("server.port"),
                (endTime - startTime) / 1000.00,
                context.getBeanDefinitionNames().length,
                Thread.currentThread().getContextClassLoader().getResource("").getPath(),
                "1.0.0-build");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值