<html>
<head>
<meta charset="UTF-8">
<title>websocket测试</title>
<style type="text/css">
h3, h4 {
text-align: center;
}
</style>
</head>
<body>
<h1>前端的信息查看控制台</h1> <script type="text/javascript">
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("遗憾:您的浏览器不支持WebSocket");
} else {
console.log("恭喜:您的浏览器支持WebSocket"); socket = new WebSocket("ws://localhost:8089/ws/asset");
//连接打开事件
socket.onopen = function () {
console.log("Socket 已打开");
socket.send("消息发送测试(From Client)");
};
//收到消息事件
socket.onmessage = function (msg) {
console.log("接收到的消息", msg.data);
};
//连接关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
}; //窗口关闭时,关闭连接
window.unload = function () {
socket.close();
};
}
</script> </body>
</html>
package com.aiguigu.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
如果是springBoot自带的嵌入式容器,则要开启
*/
@Configuration
public class WebGlobalConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

 定义webSocket类

package com.aiguigu.websocket.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger; @ServerEndpoint(value = "/ws/asset")
@Component
public class MyWebSocket {
private static Logger log = LoggerFactory.getLogger(MyWebSocket.class);
/*自增操作*/
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
// concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>(); /**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
System.out.println("建立连接");
SessionSet.add(session);
// 在线数加1,并获取最后结果
int cnt = OnlineCount.incrementAndGet();
log.info("有连接加入,当前连接数为:{}", cnt);
SendMessage(session, "连接成功xxxxx");
} /**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
SessionSet.remove(session);
int cnt = OnlineCount.decrementAndGet();
log.info("有连接关闭,当前连接数为:{}", cnt);
} /**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:{}", message);
SendMessage(session, "服务器发来的内容:" + message);
} /**
* 出现错误
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId());
error.printStackTrace();
} /**
* 发送消息,实践表明,每次浏览器刷新,session会发生变化。
*
* @param session
* @param message
*/
public static void SendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)", message, session.getId()));
} catch (IOException e) {
log.error("发送消息出错:{}", e.getMessage());
e.printStackTrace();
}
} /**
* 群发消息
*
* @param message
* @throws IOException
*/
public static void BroadCastInfo(String message) throws IOException {
for (Session session : SessionSet) {
//判断如果websocket链接如果是开启的情况下,则发送信息
if (session.isOpen()) {
SendMessage(session, message);
}
}
} /**
* 指定Session发送消息
*
* @param sessionId
* @param message
* @throws IOException
*/
public static void SendMessage(String sessionId, String message) throws IOException {
Session session = null;
for (Session s : SessionSet) {
if (s.getId().equals(sessionId)) {
session = s;
break;
}
}
if (session != null) {
SendMessage(session, message);
} else {
log.warn("没有找到你指定ID的会话:{}", sessionId);
}
} }

  定时发送

    @Scheduled(cron = "*/3 * * * * *")
@ResponseBody
@GetMapping("/websocke")
public void webSocket() {
String s = "hello world";
try {
MyWebSocket.BroadCastInfo(s);
} catch (IOException e) {
System.out.println("执行异常");
e.printStackTrace();
}
}

  入口文件开启

@SpringBootApplication
@EnableScheduling
public class WebsocketApplication { public static void main(String[] args) {
SpringApplication.run(WebsocketApplication.class, args);
} }

  前端内容

springBoot 中webSocket 应用一的更多相关文章

  1. 你知道在springboot中如何使用WebSocket吗

    一.背景   我们都知道 http 协议只能浏览器单方面向服务器发起请求获得响应,服务器不能主动向浏览器推送消息.想要实现浏览器的主动推送有两种主流实现方式: 轮询:缺点很多,但是实现简单 webso ...

  2. Springboot中的事件Event

    事件Event作为一种常用的线程通讯工具,在Springboot中可以方便地提供开发者进行线程交互. 1.事件定义 1 import org.springframework.context.Appli ...

  3. SpringBoot集成WebSocket【基于纯H5】进行点对点[一对一]和广播[一对多]实时推送

    代码全部复制,仅供自己学习用 1.环境搭建 因为在上一篇基于STOMP协议实现的WebSocket里已经有大概介绍过Web的基本情况了,所以在这篇就不多说了,我们直接进入正题吧,在SpringBoot ...

  4. SpringBoot基于websocket的网页聊天

    一.入门简介正常聊天程序需要使用消息组件ActiveMQ或者Kafka等,这里是一个Websocket入门程序. 有人有疑问这个技术有什么作用,为什么要有它?其实我们虽然有http协议,但是它有一个缺 ...

  5. springboot整合websocket原生版

    目录 HTTP缺点 HTTP websocket区别 websocket原理 使用场景 springboot整合websocket 环境准备 客户端连接 加入战队 微信公众号 主题 HTTP请求用于我 ...

  6. SpringBoot+Vue+WebSocket 实现在线聊天

    一.前言 本文将基于 SpringBoot + Vue + WebSocket 实现一个简单的在线聊天功能 页面如下: 在线体验地址:http://www.zhengqingya.com:8101 二 ...

  7. WebSocket的简单认识&SpringBoot整合websocket

    1. 什么是WebSocket?菜鸟对websocket的解释如下 WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. WebSocket 使得客户端和服务 ...

  8. springboot集成websocket的两种实现方式

    WebSocket跟常规的http协议的区别和优缺点这里大概描述一下 一.websocket与http http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能 ...

  9. springboot集成websocket实现向前端浏览器发送一个对象,发送消息操作手动触发

    工作中有这样一个需示,我们把项目中用到代码缓存到前端浏览器IndexedDB里面,当系统管理员在后台对代码进行变动操作时我们要更新前端缓存中的代码怎么做开始用想用版本方式来处理,但这样的话每次使用代码 ...

随机推荐

  1. hdu1113 Word Amalgamation(详解--map和string的运用)

    版权声明:本文为博主原创文章.未经博主同意不得转载. vasttian https://blog.csdn.net/u012860063/article/details/35338617 转载请注明出 ...

  2. VS 2013 代码注释掉,编译不执行问题

    先说说我遇到的问题吧.修改别人的代码,注释原来的代码或者添加新的代码,都不执行,还是编译原来的代码.而且还有一个错误:lc.exe 已退出 代码为 -1 解决方法: 1.先把lc.exe 已退出 代码 ...

  3. 在win7中通过手机投放媒体

    依次展开>>> 设置项 开启服务项: 和   在更给网络属性为 打开wmplayer开启两个允许 在手机端无线投屏选择设备即可

  4. 2019.1.2 Spring管理事务的方式

    Spring管理事务的方式 1.编码式 1.将核心事务管理器配置到Spring容器 2.配置TransactionTemplate模版 3.将事务模版注入service 4.在Service中调用模版 ...

  5. tensorflow训练代码

    from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mnist = input_dat ...

  6. M4修改外部晶振8M和25M晶振的方法

    共计修改三个参数: 1.HSE_VALUE   具体位置在stm32f4xx.h中 2.PLL_M          具体位置在system_stm32f4xx.c中 3.Keil编译器 工程的Opt ...

  7. STM32平台SD卡的FatFS文件系统开发

    STM32平台SD卡的FatFS文件系统开发 系统平台: STM32系列的STM32F103ZE SPI方式与SD卡通信 SD上移植FatFS系统 1 FatFS文件系统 1.1 FatFS简介 Fa ...

  8. HTML5学习总结——相关练习与项目

    一.小米商城项目 第一天示例代码: <!DOCTYPE html> <html lang="en"> <head> <meta chars ...

  9. MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

    背景描述 # Time: :: # User@Host: **[**] @ [**] Id: ** # Killed: # Query_time: Rows_examined: Rows_affect ...

  10. SQL优化例子

    如下SQL的优化: select count(*) from ( select id,name,col1,col2 from t1  where name='xxxx' union select id ...