springBoot 使用webSocket

本文(2019年6月18日 飞快的蜗牛博客)

有许多人走着走着,就迷失了自己,所以不论发生了什么,有时候抱着自己去静下来想想,要好好的对待自己;“钱塘江上潮信来,今日方知我是我”,我信奉这句话,不是我超脱了,是有时我们醒悟了;

注意标题:springboot使用websocket

1】第一步:引入依赖:

<!--集成websocket-->

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

2】第二步:配置websocket
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/** * * 使用@SpringBootApplication启动类进行启动时需要下面这段代码,****但生成war包部署在tomcat中不需要这段 * 若打成war包使用tomcat运行的话,则注释掉这个类中serverEndpointExporter 方法. * */

@Configurationpublic class WebSocketConfig {

    @Bean    public ServerEndpointExporter serverEndpointExporter() {        return new ServerEndpointExporter();    }}
3】第三步:可以在controller 下写下此类:
import org.springframework.stereotype.Component;

import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;/** * 即时通讯 */@Component@ServerEndpoint("/webSocket")public class MyWebScoketController {

    private static int onlineCount = 0;    private static CopyOnWriteArraySet<MyWebScoketController> webSocketSet = new CopyOnWriteArraySet<MyWebScoketController>();    private Session session;

    /**     * 连接建立成功调用的方法     * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据     */    @OnOpen    public void onOpen(Session session){        this.session = session;        webSocketSet.add(this);     //加入set中        addOnlineCount();           //在线数加1        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());    }    /**     * 连接关闭调用的方法     */    @OnClose    public void onClose(){        webSocketSet.remove(this);  //从set中删除        subOnlineCount();           //在线数减1        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());    }    /**     * 收到客户端消息后调用的方法     * @param message 客户端发送过来的消息     * @param session 可选的参数     */    @OnMessage    public void onMessage(String message, Session session) {        System.out.println("来自客户端的消息:" + message);        //群发消息        for(MyWebScoketController item: webSocketSet){            try {                item.sendMessage(message);            } catch (IOException e) {                e.printStackTrace();                continue;            }        }    }    @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);    }

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

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

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

}
4】第四步:在前端写个公共myWebsocket.js 如下
if("WebSocket" in window){   console.log("this browser supports websocket...");   var webSocket=new WebSocket("ws://"+window.location.host+"/XXXX/webSocket");}else{   console.log("this browser does not supports websocket...");}webSocket.onerror=function(){   console.log("链接错误...");}webSocket.onopen=function(){   console.log("链接成功...");}

/* * 哪个页面使用哪个页面加 * webSocket.onmessage=function(event){   alert(event);}*/webSocket.onclose=function(){   console.log("链接关闭...");}window.onbeforeunload=function(){   console.log("窗口即将关闭,准备关闭链接...");   webSocket.close();}function webSend(){   webSocket.send(decodeURIComponent($("#form1").serialize(),true));}function SendMesaage(mes){   webSocket.send(mes);}var closeConn=function(){   webSocket.close();}
5】第五步:测试  现在页面引入
<script type="text/javascript" src="static/js/common/myWebSocket.js"></script>
在发送消息端写下:SendMesaage(1300);

接收端写下:

webSocket.onmessage=function(event){
  此处可以接收到消息
}





原文地址:https://www.cnblogs.com/luojiesheng/p/11046161.html

时间: 2024-08-30 16:29:13

springBoot 使用webSocket的相关文章

springboot整合websocket(1)

一.背景 ??我们都知道http协议只能浏览器单方面向服务器发起请求获得响应,服务器不能主动向浏览器推送消息.想要实现浏览器的主动推送有两种主流实现方式: 轮询:缺点很多,但是实现简单 websocket:在浏览器和服务器之间建立tcp连接,实现全双工通信 ??springboot使用websocket有两种方式,一种是实现简单的websocket,另外一种是实现STOMP协议.这一篇实现简单的websocket,STOMP下一篇在讲. 注意:如下都是针对使用springboot内置容器 二.实

使用springboot+layim+websocket实现webim

使用springboot+layim+websocket实现webim 小白技术社 项目介绍 采用springboot和layim构建webim,使用websocket作为通讯协议,目前已经能够正常聊天,并没有对好友的操作进行实现,查找和加好友没有实现,有需要的可以自行实现 安装教程 sql自行导入,配置文件更改数据库信息 http://ip:8080/login 登陆入口 目前代码放在了这里 欢迎交流,点赞 原文地址:https://www.cnblogs.com/xbjss/p/982129

springboot使用WebSocket

目录 springboot使用WebSocket 前端: 后端 springboot使用WebSocket 来源:https://blog.lqdev.cn/2018/08/14/springboot/chapter-nineteen/ 类似聊天室的功能, WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议. 在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道.两者之间就直接可以数据互相传送. 浏览器

springboot集成websocket的两种实现方式

WebSocket跟常规的http协议的区别和优缺点这里大概描述一下 一.websocket与http http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能发送信息.http链接分为短链接,长链接,短链接是每次请求都要三次握手才能发送自己的信息.即每一个request对应一个response.长链接是在一定的期限内保持链接.保持TCP连接不断开.客户端与服务器通信,必须要有客户端发起然后服务器返回结果.客户端是主动的,服务器是被动的. WebSocke

SpringBoot+Vue+WebSocket 实现在线聊天

一.前言 本文将基于 SpringBoot + Vue + WebSocket 实现一个简单的在线聊天功能 页面如下: 在线体验地址:http://www.zhengqingya.com:8101 二.SpringBoot + Vue + WebSocket 实现在线聊天 1.引入websocket依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-bo

【SpringBoot】WebSocket 服务器发送事件

前言: 必需学会SpringBoot基础知识 简介: Takes an opinionated view of building production-ready Spring applications. Spring Boot favors convention over configuration and is designed to get you up and running as quickly as possible. 工具: JDK8 apache-maven-3.5.2 Inte

springboot集成websocket

websocket是全双工通信协议,目前html5支持,如果是app端的话可能不支持,建议app端实现通过tcp握手长连接实现通信,这里暂不研究. 首先websocket是一个协议,需要了解一下 第一步先引入starter 1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-websocket</artifactId

springboot整合websocket实现一对一消息推送和广播消息推送

maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> 常量类 //webSocket相关配置 //链接地址 public static String WEBSOCKETPATHPERFIX = "/ws-push&

springboot整合websocket实现客户端与服务端通信

定义 ?WebSocket是通过单个TCP连接提供全双工(双向通信)通信信道的计算机通信协议.此WebSocket API可在用户的浏览器和服务器之间进行双向通信.用户可以向服务器发送消息并接收事件驱动的响应,而无需轮询服务器. 它可以让多个用户连接到同一个实时服务器,并通过API进行通信并立即获得响应. 案例介绍 ? 后端在接收到用户新下的订单后,通知到后台系统 服务端代码 pom.xml <dependency> <groupId>org.springframework.boo