环境

window7,IntelliJ IDEA 2019.2 x64

背景:利用IntelliJ来搭建springboot框架,之后来实现websocket的功能。websocket只是实现了画面上的消息的互相推送的功能,即在不刷新网页的情况下,把必要的消息推送到你的网页上面。

利用IntelliJ来搭建spring的web框架。

1. 下载IntelliJ的安装包,之后正常安装即可

2. 打开IDE,创建一个web功能

具体操作如下

点击finish之后,自己的springweb的工程创建完了。

构建自己的websocket程序

工程的构成如下图

创建自己的control文件

LoginControl类是为了加载首页,找到webSocketIndex.html文件,但此时的application.properties文件里面要引用【spring.thymeleaf.prefix=classpath:/templates/】否则找不到路径

  1. package com.control;
  2.  
  3. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import org.springframework.web.servlet.ModelAndView;
  8.  
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11.  
  12. @EnableAutoConfiguration
  13. @RestController
  14. public class LoginControl {
  15.  
  16. @RequestMapping("login")
  17. public ModelAndView home(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
  18. String userName = "Jef";
  19. int count = 100;
        // 固定的写法
  20. ModelAndView mv = new ModelAndView("webSocketIndex");
  21. return mv;
  22. }
  23. }

application.properties文件

  1. spring.thymeleaf.prefix=classpath:/templates/
  2. server.port=8081

pom文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.7.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>demo</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>demo</name>
  15. <description>Demo project for Spring Boot</description>
  16.  
  17. <properties>
  18. <java.version>1.8</java.version>
  19. </properties>
  20.  
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-web</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-websocket</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-test</artifactId>
  33. <scope>test</scope>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  38. </dependency>
  39. </dependencies>
  40.  
  41. <build>
  42. <plugins>
  43. <plugin>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-maven-plugin</artifactId>
  46. </plugin>
  47. </plugins>
  48. </build>
  49.  
  50. </project>
  1. WebSocketServer文件
  1. package com.control;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Component;
  6.  
  7. import javax.websocket.*;
  8. import javax.websocket.server.PathParam;
  9. import javax.websocket.server.ServerEndpoint;
  10. import java.io.IOException;
  11. import java.util.List;
  12. import java.util.concurrent.ConcurrentHashMap;
  13. import java.util.concurrent.CopyOnWriteArraySet;
  14.  
  15. //@ServerEndpoint(value ="/WebSocket/{id}/{name}")
  16. @ServerEndpoint(value ="/WebSocket")
  17. @Component
  18. public class WebSocketServer {
  19. //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
  20. private static int onlineCount = 0;
  21.  
  22. //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
  23. private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
  24.  
  25. private static ConcurrentHashMap<String, List<WebSocketServer>> webSocketMap =
  26. new ConcurrentHashMap<>(3);
  27.  
  28. //与某个客户端的连接会话,需要通过它来给客户端发送数据
  29. private Session session;
  30.  
  31. private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
  32.  
  33. @OnOpen
  34. public void onOpen(Session session) throws Exception {
  35.  
  36. this.session = session;
  37. System.out.println(this.session.getId());
  38. webSocketSet.add(this); //加入set中
  39. addOnlineCount(); //在线数加1
  40. System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
  41. LOGGER.info("Open a websocket. id={}", "12");
  42.  
  43. // try {
  44. // sendMessage(CommonConstant.CURRENT_WANGING_NUMBER.toString());
  45. // } catch (IOException e) {
  46. // System.out.println("IO异常");
  47. // }
  48. }
  49.  
  50. /**
  51. * 连接关闭调用的方法
  52. */
  53. @OnClose
  54. public void onClose() {
  55. webSocketSet.remove(this); //从set中删除
  56. subOnlineCount(); //在线数减1
  57. System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
  58. LOGGER.info("Close a websocket. ");
  59. }
  60.  
  61. /**
  62. * 收到客户端消息后调用的方法
  63. *
  64. * @param message 客户端发送过来的消息*/
  65. @OnMessage
  66. public void onMessage(String message, Session session) {
  67. System.out.println("来自客户端的消息:" + message);
  68. LOGGER.info("Receive a message from client: " + message);
  69.  
  70. //群发消息
  71. for (WebSocketServer item : webSocketSet) {
  72. try {
  73. item.sendMessage(message);
  74. } catch (IOException e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. }
  79.  
  80. /**
  81. * 发生错误时调用
  82. */
  83. @OnError
  84. public void onError(Session session, Throwable error) {
  85. System.out.println("发生错误");
  86. LOGGER.error("Error while websocket. ", error);
  87. error.printStackTrace();
  88. }
  89.  
  90. public void sendMessage(String message) throws IOException {
  91. this.session.getBasicRemote().sendText(message);
  92. //this.session.getAsyncRemote().sendText(message);
  93. }
  94.  
  95. /**
  96. * 群发自定义消息
  97. * */
  98. public static void sendInfo(String message) throws IOException {
  99. for (WebSocketServer item : webSocketSet) {
  100. try {
  101. item.sendMessage(message);
  102. } catch (IOException e) {
  103. continue;
  104. }
  105. }
  106. }
  107.  
  108. public static synchronized int getOnlineCount() {
  109. return onlineCount;
  110. }
  111.  
  112. public static synchronized void addOnlineCount() {
  113. WebSocketServer.onlineCount++;
  114. }
  115.  
  116. public static synchronized void subOnlineCount() {
  117. WebSocketServer.onlineCount--;
  118. }
  119. }

html5文件

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. Welcome<br/>
  9. <input id="text" type="text" />
  10. <button onclick="connect()">Connect</button>
  11. <button onclick="send()">Send</button>
  12. <button onclick="closeWebSocket()">Close</button>
  13. <div id="message">
  14. </div>
  15. </body>
  16.  
  17. <script type="text/javascript">
  18. var websocket = null;
  19.  
  20. //判断当前浏览器是否支持WebSocket
  21. if('WebSocket' in window){
  22. debugger
  23. websocket = new WebSocket("ws://localhost:8081/WebSocket");
  24. }
  25. else{
  26. alert('Not support websocket')
  27. }
  28.  
  29. //连接发生错误的回调方法
  30. websocket.onerror = function(){
  31. debugger
  32. setMessageInnerHTML("error");
  33. };
  34.  
  35. //连接成功建立的回调方法
  36. websocket.onopen = function(event){
  37. debugger
  38. setMessageInnerHTML("open");
  39. }
  40.  
  41. //接收到消息的回调方法
  42. websocket.onmessage = function(event){
  43. debugger
  44. setMessageInnerHTML(event.data);
  45. }
  46.  
  47. //连接关闭的回调方法
  48. websocket.onclose = function(){
  49. setMessageInnerHTML("close");
  50. }
  51.  
  52. //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  53. window.onbeforeunload = function(){
  54. websocket.close();
  55. }
  56.  
  57. //将消息显示在网页上
  58. function setMessageInnerHTML(innerHTML){
  59. document.getElementById('message').innerHTML += innerHTML + '<br/>';
  60. }
  61.  
  62. //关闭连接
  63. function closeWebSocket(){
  64. websocket.close();
  65. }
  66.  
  67. //发送消息
  68. function send(){
  69. var message = document.getElementById('text').value;
  70. websocket.send(message);
  71. }
  72. </script>
  73. </html>

在做的过程中遇到的问题是【websocket = new WebSocket("ws://localhost:8081/WebSocket");】总是访问不到,这时你要确认你的【ws://localhost:8081/WebSocket】是否写错

自己检查一下即可。

运行

利用Google浏览器和IE浏览器打开网页http://localhost:8081/login,效果如下

Google浏览器

IE浏览器

Google浏览器

IE浏览器

html5+springboot+websocket的简单实现的更多相关文章

  1. springboot+websocket实现简单的在线聊天功能

    效果如下: java实现逻辑: 1.引入maven依赖 <dependency> <groupId>org.springframework.boot</groupId&g ...

  2. 使用Html5下WebSocket搭建简易聊天室

    一.Html5WebSocket介绍 WebSocket protocol 是HTML5一种新的协议(protocol).它是实现了浏览器与服务器全双工通信(full-duplex). 现在,很多网站 ...

  3. springboot搭建一个简单的websocket的实时推送应用

    说一下实用springboot搭建一个简单的websocket 的实时推送应用 websocket是什么 WebSocket是一种在单个TCP连接上进行全双工通信的协议 我们以前用的http协议只能单 ...

  4. Java Springboot webSocket简单实现,调接口推送消息到客户端socket

    Java Springboot webSocket简单实现,调接口推送消息到客户端socket 后台一般作为webSocket服务器,前台作为client.真实场景可能是后台程序在运行时(满足一定条件 ...

  5. springboot+websocket+sockjs进行消息推送【基于STOMP协议】

    springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...

  6. 认识HTML5的WebSocket

    在HTML5规范中,我最喜欢的Web技术就是正迅速变得流行的WebSocket API.WebSocket提供了一个受欢迎的技术,以替代我们过去几年一直在用的Ajax技术.这个新的API提供了一个方法 ...

  7. HTML5之WebSocket

    在HTML5规范中,我最喜欢的Web技术就是正迅速变得流行的WebSocket API.WebSocket提供了一个受欢迎的技术,以替代我们过去几年一直在用的Ajax技术.这个新的API提供了一个方法 ...

  8. HTML5的Websocket(理论篇 I)

    HTML5的Websocket(理论篇 I) ** 先请来TA的邻居:** http:无状态.基于tcp请求/响应模式的应用层协议 (A:哎呀,上次你请我吃饭了么? B:我想想, 上次请你吃了么) t ...

  9. html5利用websocket完成的推送功能(tomcat)

    html5利用websocket完成的推送功能(tomcat) 利用websocket和java完成的消息推送功能,服务器用的是tomcat7.0.42,一些东西是自己琢磨的,也不知道恰不恰当,不恰当 ...

随机推荐

  1. python 添加Windows权限

    # -*- coding: utf-8 -*- """ Created on Mon Jan 8 09:09:51 2018 @author: coordinate &q ...

  2. 微信小程序——选择某个区间的数字

    很久没有更新文章啦~~记录下今天弄的一个小功能. 先上图: 需求很简单: 第1列改变的时候,第2列也随着改变,并且比第1列大1k. 这里用到了微信的picker 组件,对于不太熟练这个组件的小伙伴可以 ...

  3. VisualStudio 2019 Serials

    9DP6T-9AGWG-KWV33-9MPC8-JDCVF 7G2HE-JR8KL-ABB9D-Y7789-GLNFL U2PWU-H7D9H-69T3B-JEYC2-3R2NG R8R8P-MTT6 ...

  4. CLR内部异常(中)

    不捕捉某一个异常 常常有这种情况,代码不需要捕捉异常,但需要执行一些清理或者修正操作.虽然不总是,支持物(holders)经常用在这种场景里.在支持物(holders)不适用的情况里,CLR提供了两个 ...

  5. pgloader 学习(五)pgloader 参考手册

    pgloader将各种来源的数据加载到PostgreSQL中.它可以转换动态读取的数据,并在加载前后提交原始SQL. 它使用COPY PostgreSQL协议将数据流式传输到服务器,并通过填充一对re ...

  6. xamarin/xamarin.forms 在锁屏电源唤醒时保持后台运行

    PARTIAL_WAKE_LOCK:保持CPU 运转,屏幕和键盘灯有可能是关闭的. SCREEN_DIM_WAKE_LOCK:保持CPU 运转,允许保持屏幕显示但有可能是灰的,允许关闭键盘灯 SCRE ...

  7. 【区间DP】加分二叉树

    https://www.luogu.org/problemnew/show/P1040#sub 题目描述 设一个n个节点的二叉树tree的中序遍历为(1,2,3,…,n),其中数字1,2,3,…,n为 ...

  8. Cocos Creator开发hello World

    若本号内容有做得不到位的地方(比如:涉及版权或其他问题),请及时联系我们进行整改即可,会在第一时间进行处理. 请点赞!因为你们的赞同/鼓励是我写作的最大动力! 欢迎关注达叔小生的简书! 这是一个有质量 ...

  9. 查看服务器内存、CPU、网络等占用情况的命令--汇总

    搭建测试环境过程中,需要对正在使用的aws服务器(实际这是一台虚拟出来的服务器),查看它在运行脚本,启动脚本时的内存,CPU,网络等使用情况 1.查看服务器cpu内核个数: -cat 每个物理cpu中 ...

  10. 微信小程序 movable-view组件应用:可拖动悬浮框_返回首页

    1. movable-view组件具体内容可参考官网:微信官方文档 2. demo参考:https://github.com/ChinaFanny/YFWeappMovableView 运行效果 核心 ...