<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. 【xampp】windows下XAMPP集成环境中,MySQL数据库的使用

    在已经安装了XAMPP之后,会在你安装的目录下面出现”XAMPP“文件夹,这个文件夹就是整个XAMPP集成环境的目录. 我们先进入这个目录,然后会看到带有XAMPP标志的xampp-control.e ...

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

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

  3. CPP-基础:临界区

    VC windows api 多线程---临界区 临界区(Critical Section)是一段独占对某些共享资源访问的代码,在任意时刻只允许一个线程对共享资源进行访问.如果有多个线程试图同时访问临 ...

  4. Apple的UIAutomation环境搭建和入门知识

    简述 Xcode的instruments中的Automation是为了实现自动化测试的一个工具.实现方式有两种:它提供了两种实现方式, 1)     是通过JS脚本语言来执行自动化测试(普通自动化测试 ...

  5. 转:javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure 解决方案

    转:javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure 解决方案javax.net.ssl.SSL ...

  6. 使用Scanner将InputStream类型转换成String

    我们在测试项目中经常会遇到这样的情形: 1. 从文件或网络得到一个InputStream,需要转换成String赋值到别的变量做为另一个方法的入参. 2. 从文件或网络得到一个InputStream后 ...

  7. 清除IE8/IE9/IE10/IE11浏览器缓存文件 100%有效

    不管你是哪个版本的IE浏览器,按照下面指示操作,都能清除掉你使用浑身解数也清不掉的缓存文件! 第一步,打开IE浏览器——工具——Internet选项 有的IE浏览器的Internet选项藏在右上角一个 ...

  8. FastReport.net分组排序、打印顺序、分页、函数使用语法、数据块编辑

    本人使用的是FastReport.net1.0版,不涉及到任何代码,只是在FastReport中对打印模板的属性进行调整 1.设置打印顺序需要注意的属性 1)分组页眉中有个属性叫“condition” ...

  9. iOS:CALayer(17-12-06更)

    目录 1.CALayer(父类) 2.CAShapeLayer(形状/画布) 3.CAEmitterLayer(粒子发射层) 4.CAGradientLayer(渐变层) 5.CATransformL ...

  10. 学习笔记(1)centos7 下安装nginx

    学习笔记(1)centos7 下安装nginx 这里我是通过来自nginx.org的nginx软件包进行安装的. 1.首先为centos设置添加nginx的yum存储库 1.通过vi命令创建一个rep ...