java Springboot 整合 WebSocket 简单、明了、贴了就好使的一篇博客

SpringBoot 整合WebSocket

不废话,上代码,贴了就好使!

java端代码

import com.alibaba.fastjson.JSON;
import com.zmj.digitalworkshop.panel.dip.angle.entity.Message;
import io.swagger.annotations.ApiOperation;
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.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * webSocket
 *
 * pom.xml 需要引入如下:
 * <dependency>
 *  <groupId>org.springframework.boot</groupId>
 *  <artifactId>spring-boot-starter-websocket</artifactId>
 *  <version>2.1.6.RELEASE</version>
 * </dependency>
 */
@Component
@ServerEndpoint("/webSocket/{username}")
public class WebSocketServer {
    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static AtomicInteger onlineNum = new AtomicInteger();

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

    /**
     * 建立连接成功调用
     * @param session:webSocket 信息
     * @param userName:用户名
     * @throws IOException
     * @throws InterruptedException
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "username") String userName) throws IOException, InterruptedException {
        sessionPools.put(userName, session);
        // 当前在线人数+1
        addOnlineCount();
        System.out.println(userName + "加入webSocket!当前人数为" + onlineNum);
        // 广播上线消息
        /*Message msg = new Message();
        msg.setDate(new Date());
        msg.setType("0");
        msg.setContent(userName);
        broadcast(JSON.toJSONString(msg,true));*/
    }

    /**
     * 关闭连接时调用
     * @param userName:用户名称
     * @throws IOException
     */
    @OnClose
    @ApiOperation(value = "获取当前在线用户数量及列表", notes = "获取当前在线用户数量及列表", httpMethod = "WS")
    public void onClose(@PathParam(value = "username") String userName) throws IOException {
        sessionPools.remove(userName);
        // 当前在线人数-1
        subOnlineCount();
        System.out.println(userName + "断开webSocket连接!当前人数为" + onlineNum);
        // 广播下线消息(视需求而用)
        /*Message msg = new Message();
        msg.setDate(new Date());
        msg.setType("-2");
        msg.setContent(userName);
        broadcast(JSON.toJSONString(msg,true));*/
    }

    /**
     * 给指定用户发送信息
     * @param userName:用户名称
     * @param message:要发送的内容
     */
    public static void sendInfo(String userName, String message){
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     * @param message:要发送的消息
     */
    public void broadcast(String message){
        for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 发送消息
     * @param session:该用户的webSocket 信息
     * @param message:要发送的信息
     * @throws IOException
     */
    public static void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                System.out.println("发送数据:" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 收到客户端信息后,根据接收人的 username 把消息推下去或者群发
     * to = -1 群发消息
     * @param message:信息内容
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message) throws IOException{
        System.out.println("server get" + message);
        Message msg=JSON.parseObject(message, Message.class);
        msg.setDate(new Date());
        if (msg.getType().equals("-1")) {
            broadcast(JSON.toJSONString(msg,true));
        } else {
            sendInfo(msg.getType(), JSON.toJSONString(msg,true));
        }
    }

    /**
     * 错误时调用
     * @param session
     * @param throwable:错误
     */
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    /**
     * 当前在线人数+1
     */
    public static void addOnlineCount(){onlineNum.incrementAndGet();}

    /**
     * 当前在线人数-1
     */
    public static void subOnlineCount() {onlineNum.decrementAndGet();}
    
    public static AtomicInteger getOnlineNumber() {return onlineNum;}
    public static ConcurrentHashMap<String, Session> getSessionPools() {return sessionPools;}

}

前端代码

随便写了点大概意思就是这
TOM就是要链接的用户名称

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<body>
		<script>
			getWS()
			function getWS(){
			    const ws= new WebSocket('ws://127.0.0.1:8080/webSocket/TOM')
				ws.onopen = function(){
					console.log('建立链接')
				}
			}
		</script>
	</body>
</html>

要看浏览器 websocket 的数据的话,如下:
在这里插入图片描述
谷歌,F12,然后点 WS,就能看到 webSocket 的一些消息了
别看我的报红了,因为我懒,不想开项目,它连不上

要是写的还行的话,给我点动力点个赞吧
有什么问题当前页面请留言。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

槐序二十四

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值