SpringBoot + WebSocket + js -- 推送消息到前端页面

1 引入依赖

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

2 添加socket配置类

@Configuration
public class WebSocketConfig {
    /**
     * 服务器节点
     *
     * 如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3 添加WebSocketServer类

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/websocket/info/{stationId}")
@Component
@Slf4j
public class WebSocketServer {

	//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
	private volatile static int onlineCount = 0;

	//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
//	private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
	public volatile static Map<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
	
	//与某个客户端的连接会话,需要通过它来给客户端发送数据
	private Session session;

	private String stationId;

	/**
	 *  给指定客户端发送发送信息
	 * @param id 客户端id
	 * @param msg 消息
	 */
	public static void sendInfo(Long id, String msg) {
		WebSocketServer wb = webSocketMap.get(String.valueOf(id.longValue()));
		if (wb != null) {
			try {
				wb.sendMessage(msg);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 连接建立成功调用的方法
	 * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
	 */
	@OnOpen
	public void onOpen(@PathParam("stationId") String stationId, Session session){
		this.session = session;


		//获取连接的用户,以及聊天组
		this.stationId = stationId;

		//保存会话对象
		webSocketMap.put(this.stationId, this);

		addOnlineCount();           //在线数加1
		log.info("有新连接加入!当前在线连接为" + getOnlineCount());
	}

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

	/**
	 * 收到客户端消息后调用的方法
	 * @param message 客户端发送过来的消息
	 * @param session 可选的参数
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		log.info("来自客户端的消息:" + message);
		//群发消息
		for (Map.Entry<String, WebSocketServer> entry : webSocketMap.entrySet()) {
			try {
				entry.getValue().sendMessage(message);
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
		}
	}

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

	/**
	 * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
	 * @param message
	 * @throws IOException
	 */
	public void sendMessage(String message) throws IOException{
		this.session.getBasicRemote().sendText(message);
	}

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

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

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

4 添加客户端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <title>连接socket测试</title>

</head>
<body>

<script type="text/javascript">

    var websocket = null;


    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        // if (false) {
        //     websocket = new WebSocket("wss://”); //https
        // } else {
            websocket = new WebSocket("ws://localhost:8080/data-gather/websocket/running/info/1");
        // }
    } else {
        alert('当前浏览器 Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("登录成功,可以聊天咯");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessage(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        // setMessageInnerHTML("WebSocket连接关闭");
        window.opener = null;
        window.open('', '_self');
        window.close();
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }


    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        console.log(innerHTML);
    }

    //将消息显示在网页上
    function setMessage(innerHTML) {
        console.log(innerHTML);
    }


   //发送文件消息
  function send() {
      var message = document.getElementById('info').value;
      var data = {};
      data.message = message;
      data.type = 1;

      websocket.send(JSON.stringify(data));
  }

  //发送文件消息
 function sendImg(msg, type, fileName) {
     var data = {};
     data.message = msg;
     data.type = type;
     data.fileName = fileName;

     websocket.send(JSON.stringify(data));
 }

</script>
</body>

</html>

5 服务器端发送信息

WebSocketServer.sendInfo("1", "你好");

6 测试

1 启动springboot项目
2 打开html页面, F12, 看到控制台打印连接结果,并接收到信息即为成功
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值