WebSocket学习(一)

用到的依赖
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-websocket</artifactId>
 </dependency>
java服务端代码
springboot配置
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
WebSocket服务

// 声明websocket的服务地址
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {
    /**
     * 静态变量,用来记录当前在线连接数。线程安全。
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收sid
     */
    private String sid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session; //保存当前客户端的session
        webSocketSet.add(this);// 加入set中
        addOnlineCount();// 在线数加1
        System.out.println(session.getRequestURI());
        log.info("有新用户登录:" + sid + ", 当前在线人数为" + getOnlineCount());
        this.sid = sid;
    }

    /**
     * 前台连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除已关闭的连接
        subOnlineCount(); // 在线人数数减 1
        log.info("有一用户连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + sid + "的信息:" + message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage("欢迎客户登录");
        }
    }

    /**
     * 连接发生错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务器推送数据
     * @param message 消息内容
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("消息推送失败");
            e.printStackTrace();
        }
    }

    /**
     * 管理元推送全部消息给用户 一对多
     * @param message
     */
    public static void pushMessageToAllUser(String message){
        // 只要在集合中的(也就是全部用户) 就给他发送消息
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage(message);
        }
    }

    /**
     * 点对点发送消息
     */
    public static void sendInfo(String message, String sid) {
        log.info("推送消息到窗口" + sid + ",推送内容:" + message);
        for (WebSocketServer item : webSocketSet) {
            if(item.sid.equals(sid)){
                item.sendMessage(message);
            }
        }
    }

    /**
     * 获取在线人数
     * @return
     */
    public static int getOnlineCount() {
        return onlineCount.get();
    }

    /**
     * 在线人数加一
     */
    public static void addOnlineCount() {
        WebSocketServer.onlineCount.addAndGet(1);
    }

    /**
     * 在线人数减一
     */
    public static void subOnlineCount() {
        WebSocketServer.onlineCount.decrementAndGet();
    }

}

前端代码

	var socket; // 创建一个socket
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        console.log("您的浏览器支持WebSocket");
        socket = new WebSocket("ws://localhost:8080/websocket/" + 55); // 请求连接 注意一定是ws://+你的websocket服务端口
        
        //客户端与服务端成功建立连接后的回调函数
        socket.onopen = function() {
            console.log("Socket 已打开");
            socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        
        //服务端发送消息后回调函数
        socket.onmessage = function(msg) {
            console.log(msg.data);
            //发现消息进入 开始处理前端触发逻辑
            alert(msg.data)
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }
        //离开页面时,关闭socket
        //jquery1.8中已经被废弃,3.0中已经移除
        // $(window).unload(function(){
        //     socket.close();
        //});
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值