sprint boot websocket 服务端+html5 示例测试
包依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
配置类 WebSocketConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import javax.websocket.server.ServerEndpointConfig; @Configuration
public class WebSocketConfig extends ServerEndpointConfig.Configurator { public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "")
.setAllowedOrigins("*");
} public WebSocketHandler myHandler() {
return new AlarmWebSocket();
} @Bean
public ServerEndpointExporter serverEndpointExporter() {
ServerEndpointExporter serverEndpointExporter = new ServerEndpointExporter();
return serverEndpointExporter;
}
}
WebSocketTest.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.TextWebSocketHandler; import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet; @ServerEndpoint(value = "/websocketOne",configurator = WebSocketConfig.class)
@Component
public class AlarmWebSocket extends TextWebSocketHandler {
public final static Logger logger = LoggerFactory.getLogger(AlarmWebSocket.class); private static int onlineCount = 0; //用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<AlarmWebSocket> webSocketMap = new CopyOnWriteArraySet<AlarmWebSocket>();
private Session session; @OnOpen
public void onOpen(Session session) throws IOException {
this.session = session;
webSocketMap.add(this);
addOnlineCount(); this.sendMessage(""); // TODO: 建立连接推送到前端的数据
logger.info("create new webSocket connect!now WebSocket Client number is " + getOnlineCount());
} @OnClose
public void onClose(){ webSocketMap.remove(this);
subOnlineCount();
System.out.println("close one webSocket connect!now WebSocket Client is " + getOnlineCount()); } /**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println(7777); //发送的用户号就是session.hashcode(),可以再加个map继续映射
/* int pos=message.indexOf("#*#*");
String realmessage=message.substring(0,pos);
String realuser=message.substring(pos+4,message.length());*/
System.out.println("来自客户端的消息:" + message);
//
/* WebSocketTest item=webSocketMap.get(realuser);
item.sendMessage(realmessage);*/
sendMessage(message); } /**
* 群发自定义消息
*/
public static void sendInfo(String message) {
System.out.println(66666); //log.info(message); for (AlarmWebSocket item : webSocketMap) {
try {
item.sendMessage(message);
} catch (IOException e) {
//log.error("向客户端发送数据失败!", e);
//continue;
}
}
} /**
* 发生错误时调用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误");
error.printStackTrace();
} /**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
* @param message
* @throws IOException
*/
//给客户端传递消息
public void sendMessage(String message) throws IOException{ this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
} public static synchronized int getOnlineCount() {
return onlineCount;
} public static synchronized void addOnlineCount() {
AlarmWebSocket.onlineCount++;
} public static synchronized void subOnlineCount() {
AlarmWebSocket.onlineCount--;
} }
html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>RevealWebSocket</title> <script src="js/vue.js"></script> </head> <body> 接受数据<br/><br/> <div id="ws"> <input id="text" type="text"/> <button onclick="sendMsg()">Send</button> <button onclick="closeWS()" :disabled="!opened">Close</button> <button onclick="openWS()" :disabled="opened">Open</button> <div v-html="msg"></div> </div> </body> <script type="text/javascript"> var websocket = null; var wsVue = new Vue({ el: '#ws', data: { msg: "welcome to my websocket...<br/>", opened: false }, mounted: function(){ initWs(); } }); function initWs() { //check if your browser supports WebSocket if ('WebSocket' in window) { //websocket = new WebSocket("ws://124.207.211.211:85/monitor/monitor/socket");
websocket = new WebSocket("ws://localhost:9001/websocketOne");
//websocket = new WebSocket("ws://192.168.1.53:9100/monitor/websocketOne");
} else { alert('Sorry, websocket not supported by your browser.') } //Error callback websocket.onerror = function () { setMessageContent("error!"); wsVue.opened = false; }; //socket opened callback websocket.onopen = function (event) { setMessageContent("websocket opened"); wsVue.opened = true; } //message received callback websocket.onmessage = function (event) { setMessageContent(event.data); } //socket closed callback websocket.onclose = function () { setMessageContent("websocket closed"); wsVue.opened = false; } //when browser window closed, close the socket, to prevent server exception window.onbeforeunload = function () { websocket.close(); } } //update message to vue and then in div function setMessageContent(content) { wsVue.msg = content; } //click to close the websocket function closeWS() { websocket.close(); wsVue.opened = false; } //click to open the websocket function openWS() { initWs(); } //click to send message function sendMsg() { var message = document.getElementById('text').value; websocket.send(message); } </script> </body> </html>
sprint boot websocket 服务端+html5 示例测试的更多相关文章
- C# WebSocket 服务端示例代码 + HTML5客户端示例代码
WebSocket服务端 C#示例代码 using System; using System.Collections.Generic; using System.Linq; using System. ...
- 用nodejs快速实现websocket服务端(带SSL证书生成)
有不少公司将nodejs的socket.io作为websocket的解决方案,很遗憾的是socket.io是对websocket的封装,并不支持html5原始的websocket协议,微信小程序使用的 ...
- asp.net网站作为websocket服务端的应用该如何写
最近被websocket的一个问题困扰了很久,有一个需求是在web网站中搭建websocket服务.客户端通过网页与服务器建立连接,然后服务器根据ip给客户端网页发送信息. 其实,这个需求并不难,只是 ...
- Netty 搭建 WebSocket 服务端
一.编码器.解码器 ... ... @Autowired private HttpRequestHandler httpRequestHandler; @Autowired private TextW ...
- nodejs搭建简单的websocket服务端
创建websocket服务端使用了nodejs-websocket ,首先要安装nodejs-websocket,在项目的目录下: npm install nodejs-websocket 1.搭建w ...
- WebSocket服务端
http://blog.csdn.net/qq_20282263/article/details/54310737 C# 实现WebSocket服务端 原创 2017年01月10日 09:22:50 ...
- socket服务端开发之测试使用threading和gevent框架
socket服务端开发之测试使用threading和gevent框架 话题是测试下多线程和gevent在socket服务端的小包表现能力,测试的方法不太严谨,也没有用event loop + pool ...
- Netty搭建WebSocket服务端
Netty服务端 1.引入依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns=& ...
- websocket服务端开发
基于http请求以拉的方式去做服务器的推送,无论是实时性和有效字节都是差强人意的效果. 公司的im系统在与客户端的交互上实际上借助了websocket来实现服务器与客户端的事实消息推送,今天就来简单了 ...
随机推荐
- XML 中的 xmlns 等属性的意义
原文:https://blog.csdn.net/lengxiao1993/article/details/77914155 Maven 是一个 java 开发人员很难绕过的构建工具, 因为有众多的开 ...
- ImageSwitcher 图片切换器
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...
- 从0开始学爬虫9之requests库的学习之环境搭建
从0开始学爬虫9之requests库的学习之环境搭建 Requests库的环境搭建 环境:python2.7.9版本 参考文档:http://2.python-requests.org/zh_CN/l ...
- 修复gitlab服务器突然停电导致PostgreSQL损坏的数据库
最开始是存储的卷组受损,使用的DRBD,使用了xfs分区格式: 挂载也报错: mount /dev/drbd0 /var/opt mount: wrong fs type, bad option, b ...
- word正文中怎么引用章节编号、怎么引用图片表格编号、交叉引用
摘自:https://blog.csdn.net/m0_37549050/article/details/88823135 在写文档的时候,可能会出现需要在文档中引用其它段落的编号.比如文档分了章节, ...
- 转 mysql 文件系统空间满了
#######################sample [OIP - 互联网开放平台]在2019-07-28 21:30:11发生10.194.42.19 - - Linux上的监控项[磁盘空间] ...
- Vue学习笔记十:过滤器
目录 公共过滤器的写法 简易过滤器+带参数过滤器+多过滤器 私有过滤器 公共过滤器的写法 过滤器的写法还是很简单的 ,如下 <p>{{ msg | filtermsg }}</p&g ...
- expect 实现自动交互脚本
1. 说明 在编写脚本时,可能会遇到需要在另一台主机上执行一个命令,或者在本机拷贝另一台主机内的一个文件.如果两台主机之间没有做互信,就会牵扯到用户输入密码的交互过程,这对编写自动脚本来说, 就行不通 ...
- 03点睛Spring MVC 4.1-REST
转发:https://www.iteye.com/blog/wiselyman-2214290 3.1 REST REST:Representational State Transfer; REST是 ...
- 【ARTS】01_44_左耳听风-201900909~201900915
ARTS: Algrothm: leetcode算法题目 Review: 阅读并且点评一篇英文技术文章 Tip/Techni: 学习一个技术技巧 Share: 分享一篇有观点和思考的技术文章 Algo ...