spring boot + webSocket 实现简单会话与在线人数统计的demo

webSocket推送是常用于生产项目的模块,在我们部门做的一个汇报演示的demo中遇到了webSocket的一些问题。

自己下来看看了看webSocket的东西,结合spring boot 做了一个简单的demo;

介绍的部分大家可以参考众多的帖子,度娘

http://www.cnblogs.com/wei2yi/archive/2011/03/23/1992830.html

http://my.oschina.net/ldl123292/blog/304360


好的,现在贴一下我的代码 注释写的很细,也很简单,一下就能看懂。



java:

package com.haungteng.springboot.controller.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author ht
 * @describle 统计在线人数的demo
 */

@Component
@ServerEndpoint("/websocket")  //该注解表示该类被声明为一个webSocket终端
public class MySocket {
    //初始在线人数
    private static int online_num = 0;
    //线程安全的socket集合
    private static CopyOnWriteArraySet<MySocket> webSocketSet = new CopyOnWriteArraySet<MySocket>();
    //会话
    private Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        System.out.println("有链接加入,当前人数为:"+getOnline_num());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有链接关闭,当前人数为:"+getOnline_num());
    }

    @OnMessage
    public void onMessage(String message,Session session) throws IOException{
        System.out.println("来自客户端的消息:"+message);
        for(MySocket item:webSocketSet){
            this.session.getAsyncRemote().sendText("hello");
        }
    }
    public synchronized int getOnline_num(){
        return MySocket.online_num;
    }
    public synchronized int subOnlineCount(){
        return MySocket.online_num--;
    }
    public synchronized int addOnlineCount(){
        return MySocket.online_num++;
    }
}

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My WebSocket</title>
</head>
<body>
    <h2 οnclick="openTanTan()" style="color:dodgerblue;text-align: center">WeTanTan</h2>
    <div id="tantanbox" style="width:800px;height:498
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值