从零玩转Websocket实时通讯服务之前后端分离版本
前言
公司项目需要用到消息提示,那么WebSocket它来了经过我面向百度的学习,废话不多说直接开干.
后端搭建
一、依赖导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、搭建websocket服务
1.WebSocketConfig配置文件
/*==============================================================================
= - Yang Buyi Copyright (c) 2021 https://yangbuyi.top.
=============================================================================*/
package top.yangbuyi.service_websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 配置文件
*
* @author Yang Buyi
* @date 2021/10/25
*/
@Configuration
public class WebSocketConfig {
/**
* 给Spring容器注入 ServerEndpointExporter 对象
*
* @return {@link ServerEndpointExporter}
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.WebSocketServer服务
/*==============================================================================
= - Yang Buyi Copyright (c) 2021 https://yangbuyi.top.
=============================================================================*/
package top.yangbuyi.service_websocket.server;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* websocket前端请求服务地址
*
* /service_websocket/wspoint/yangbuyi
*
* @author Yang Buyi
* @date 2021/10/25
*/
@ServerEndpoint("/service_websocket/wspoint/{loginName}")
@Component
public class WebSocketServer {
/**
* 存储每一个连接
*/
private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
/**
* 会话
*/
private Session session;
/**
* 登录名
*/
private String loginName = "";
/**
* 在开放
*
* @param session 会话
* @param loginName 登录名
*/
@OnOpen
public void onOpen(Session session, @PathParam("loginName") String loginName) {
// 前端连接得到登陆名称
this.loginName = loginName;
// 当前websokcet生成的会话
this.session = session;
webSocketSet.add(this);
try {
sendMessage("success");
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 在关闭
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
}
/**
* 在消息
*
* @param message 消息
* @param session 会话
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("接收到来自[" + message + "]发送的消息" + session);
// 发送消息
// for (WebSocketServer item : webSocketSet) {
// try {
// item.sendMessage(message + ",时间:" + new Date() + session);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
/**
* 在错误
*
* @param session 会话
* @param error 错误
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
/**
* 发送消息
*
* @param message 消息
*/
public void sendMessage(String message) {
try {
// 建议加个同步锁
if (this.session != null) {
this.session.getBasicRemote().sendText(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发送信息
* 发送指定消息给某个用户
*
* @param userName 用户名
* @param msgStr 消息信息
*/
public static void sendInfo(String userName, String msgStr) {
for (WebSocketServer item : webSocketSet) {
if (item.loginName.equals(userName)) {
item.sendMessage(msgStr);
}
}
}
}
前端搭建
一、index.vue
<!--============================================================================
= - Yang Buyi Copyright (c) 2021 https://yangbuyi.top.
===========================================================================-->
<template>
<div class="webSocket">
<button id="send" class="btn btn-default" @click="sendMsg('发送杨不易https://yangbuyi.top')">Send</button>
<div v-for="item in msgData" :key="item">
{{ item }}
</div>
</div>
</template>
<script>
export default {
name: 'WebSocket',
data() {
return {
// 消息
msgData: [],
websocket: null
}
},
mounted() {
this.connection()
// this.initWebSocket()
},
destroyed() {
if (this.websocket != null) this.websocket.close() // 离开路由之后断开websocket连接
},
methods: {
initWebSocket() {
this.connection()
// const that = this
// // 断开重连机制,尝试发送消息,捕获异常发生时重连
// this.timer = setInterval(() => {
// try {
// that.websocket.send('hello')
// } catch (err) {
// console.log('断线了: ' + err)
// that.connection()
// }
// }, 5000)
},
/**
* 连接后台ws
*/
connection() {
const socketUrl = 'ws://localhost:你服务的端口/service_websocket/wspoint/' + '唯一名称'
if (typeof (WebSocket) === 'undefined') {
console.log('您的浏览器不支持WebSocket')
this.$message.error('您的浏览器不支持WebSocket,无法使用推送功能!')
} else {
this.websocket = new WebSocket(socketUrl)
console.log(this.websocket)
this.websocket.onopen = this.websocketOnopen // 连接成功
this.websocket.onmessage = this.websocketOnmessage // 广播成功
this.websocket.onerror = this.websocketOnerror // 连接断开,失败
this.websocket.onclose = this.websocketClose // 连接关闭
}
},
websocketOnopen() {
this.sendMsg('连接成功第一次https://yangbuyi.top')
console.log('连接成功')
},
websocketOnerror() {
console.log('连接失败')
},
websocketClose() {
console.log('断开连接')
},
websocketOnmessage(data) {
this.msgData.push(data)
},
sendMsg(val) {
this.websocket.send(val)
}
}
}
</script>
从零玩转Websocket实时通讯服务之前后端分离版本的更多相关文章
- 使用tomcat方式实现websocket即时通讯服务端讲解
使用tomcat方式实现websocket即时通讯服务端讲解 第一种方案:使用Tomcat的方式实现 tomcat版本要求:tomcat7.0+.需要支持Javaee7 导入javeee-api的ja ...
- Uniapp使用GoEasy实现websocket实时通讯
Uniapp作为近来最火的移动端开发技术,一套代码,可以打包成Android/iOS app和各种平台的小程序,可谓是没有最方便只有更方便. GoEasy上架DCloud Uniapp插件市场已经有一 ...
- 微信小程序使用GoEasy实现websocket实时通讯
不需要下载安装,便可以在微信好友.微信群之间快速的转发,用户只需要扫码或者在微信里点击,就可以立即运行,有着近似APP的用户体验,使得微信小程序成为全民热爱的好东西~ 同时因为微信小程序使用的是Jav ...
- Webapi实现websocket实时通讯
应用场景:前端页面发起一个websocket请求与后端进行实时通讯.后端监听某端口获取数据,将监听到的数据加工处理,通过websocket发送到前端. 这里只提供后台的处理方案仅供参考. 1.后端监听 ...
- 零配置Socket TCP消息通讯服务容器EC
EC全称是elastic communication,是基于c#实现的Socket网络通讯服务容器,支持windows .Net和mono.通过EC容器可以让开发人员在不了解Socket网络通讯知识和 ...
- 使用Websocket框架之GatewayWorker开发电商平台买家与卖家实时通讯
前段时间公司提了一个新的需求,在商品的详情页要实现站内买家和商品卖家实时通讯的功能以方便沟通促成交易,要开发此功能当时首先考虑到的就是swoole和workerman了,从网上大概了解了一下关于这两款 ...
- 基于TP5使用Websocket框架之GatewayWorker开发电商平台买家与卖家实时通讯
https://www.cnblogs.com/wt645631686/p/7366924.html 前段时间公司提了一个新的需求,在商品的详情页要实现站内买家和商品卖家实时通讯的功能以方便沟通促成交 ...
- Java开发之使用websocket实现web客户端与服务器之间的实时通讯
使用websocket实现web客户端与服务器之间的实时通讯.以下是个简单的demo. 前端页面 <%@ page language="java" contentType=& ...
- PHP基于TP5使用Websocket框架之GatewayWorker开发电商平台买家与卖家实时通讯
前段时间公司提了一个新的需求,在商品的详情页要实现站内买家和商品卖家实时通讯的功能以方便沟通促成交易,要开发此功能当时首先考虑到的就是swoole和workerman了,从网上大概了解了一下关于这两款 ...
- 微信小程序实时通讯(websocket)问题
这几天值班忙的不要不要,人工智能这块看的都是零零散散,今天就来写写小程序的实时通讯吧.小程序端://这个是连接 lianjie:function(){ var socketOpen = false / ...
随机推荐
- python基础:元组(tuple)列表(list)介绍
一,元组 1.元组的创建(可以把元组看作一个容器,任何数据类型都可以放在里面)通过赋值方法创建元组In [5]: t = ("hello",2.3,2,True,{1:" ...
- Solution -「CF 1303G」Sum of Prefix Sums
Description Link. 对于一棵树,选出一条链 \((u,v)\),把链上结点从 \(u\) 到 \(v\) 放成一个 长度 \(l\) 的数组,使得 \(\sum_{i=1}^{l}\s ...
- C++指针和地址偏移在HotSpot VM中的应用
在前面我们介绍过new运算符,这个操作实际上上包含了如下3个步骤: 调用operator new的标准库函数.此函数会分配一块内存空间以便函存储相应类型的实例. 调用相应类的构造函数 返回一个指向该对 ...
- 解锁Java面试中的锁:深入了解不同类型的锁和它们的用途
简介 多线程编程在现代软件开发中扮演着至关重要的角色.它使我们能够有效地利用多核处理器和提高应用程序的性能.然而,多线程编程也伴随着一系列挑战,其中最重要的之一就是处理共享资源的线程安全性.在这个领域 ...
- vue~封装一个文本框添加与删除的组件
标签组件的效果如下 组件作用 这是一个div,包含了两个文本框,后面是添加和删除按钮 添加按钮复制出新的div,除了文本框没有内容,其它都上面一样 删除按钮将当前行div删除 组件实现 <tem ...
- 【matplotlib 实战】--堆叠面积图
堆叠面积图和面积图都是用于展示数据随时间变化趋势的统计图表,但它们的特点有所不同.面积图的特点在于它能够直观地展示数量之间的关系,而且不需要标注数据点,可以轻松地观察数据的变化趋势.而堆叠面积图则更适 ...
- Arduino 麦克风声音传感器指南
麦克风声音传感器 麦克风声音传感器,顾名思义,检测声音.它可以测量声音的响度. 这些传感器的种类繁多. 在下图中,您可以看到 Arduino 最常用的. 最左边是KY-038,右边是LM393麦克风 ...
- 【接口测试】如何在 Eolink Apilkit 中使用 cookie ?
什么是 Cookie ? Cookie是一种在网站之间传递的小型文本文件,用于存储用户的个人信息和偏好设置.当您访问一个网站时,网站会将Cookie存储在您的浏览器中,并在您下次访问该网站时读取该Co ...
- 软件开发人员 Kubernetes 入门指南|Part 2
在第 1 部分中,我们讲解了 Kubernetes 的核心组件,Kubernetes 是一种开源容器编排器,用于在分布式环境中部署和扩展应用程序:我们还讲解了如何在集群中部署一个简单的应用程序,然后更 ...
- 高效技巧揭秘:Java轻松批量插入或删除Excel行列操作
摘要:本文由葡萄城技术团队原创并首发.转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者. 前言 在职场生活中,对Excel工作表的行和列进行操作是非常普遍的需求 ...