简介
websocket 是一种全双工通信协议,用于在 web 浏览器和服务器之间建立持久的连接。
- websocket 协议由 ietf 定为标准,websocket api 由 w3c 定为标准。
- 一旦 web 客户端与服务器建立连接,之后的全部数据通信都通过这个连接进行。
- 可以互相发送 json、xml、html 或图片等任意格式的数据。
websocket 与 http 协议的异同:
相同点:
- 都是基于 tcp 的应用层协议。
- 都使用 request/response 模型进行连接的建立。
- 可以在网络中传输数据。
不同点:
- websocket 使用 http 来建立连接,但定义了一系列新的 header 域,这些域在 http 中并不会使用。
- websocket 支持持久连接,而 http 协议不支持持久连接。
websocket 优点:
高效性: 允许在一条 websocket 连接上同时并发多个请求,避免了传统 http 请求的多个 tcp 连接。
websocket 的长连接特性提高了效率,避免了 tcp 慢启动和连接握手的开销。
节省带宽:http 协议的头部较大,且请求中的大部分头部内容是重复的。websocket 复用长连接,避免了这一问题。
服务器推送:websocket 支持服务器主动推送消息,实现实时消息通知。
websocket 缺点:
长期维护成本:服务器需要维护长连接,成本较高。
浏览器兼容性:不同浏览器对 websocket 的支持程度不一致。
受网络限制:websocket 是长连接,受网络限制较大,需要处理好重连。
websocket 应用场景:
- 实时通信领域:
- 社交聊天弹幕
- 多玩家游戏
- 协同编辑
- 股票基金实时报价
- 体育实况更新
- 视频会议/聊天
- 基于位置的应用
- 在线教育
- 智能家居等需要高实时性的场景。
一、后端代码
1、安装核心jar包: spring-boot-starter-websocket
<dependencies>
<!-- springboot websocket -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-websocket</artifactid>
</dependency>
<dependency>
<groupid>cn.hutool</groupid>
<artifactid>hutool-all</artifactid>
<version>5.1.0</version>
</dependency>
<dependency>
<groupid>com.alibaba</groupid>
<artifactid>fastjson</artifactid>
<version>2.0.22</version>
</dependency>
</dependencies>
2. 来一个配置类注入
package com.codese.config;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.web.socket.server.standard.serverendpointexporter;
@configuration
public class websocketconfig2 {
@bean
public serverendpointexporter serverendpointexporter(){
return new serverendpointexporter();
}
}
3. 写个基础websocket服务
import cn.hutool.log.log;
import cn.hutool.log.logfactory;
import com.alibaba.fastjson.json;
import com.alibaba.fastjson.jsonobject;
//import org.apache.commons.lang3.stringutils;
import org.springframework.stereotype.component;
import org.springframework.util.stringutils;
import javax.websocket.*;
import javax.websocket.server.pathparam;
import javax.websocket.server.serverendpoint;
import java.io.ioexception;
import java.util.concurrent.concurrenthashmap;
/**
* @classname: 开启websocket支持
*/
@serverendpoint("/dev-api/websocket/{userid}")
@component
public class websocketserver {
static log log = logfactory.get(websocketserver.class);
/**
* 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
*/
private static int onlinecount = 0;
/**
* concurrent包的线程安全set,用来存放每个客户端对应的mywebsocket对象。
*/
private static concurrenthashmap<string, websocketserver> websocketmap = new concurrenthashmap<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private session session;
/**
* 接收userid
*/
private string userid = "";
/**
* 连接建立成功调用的方法
*/
@onopen
public void onopen(session session, @pathparam("userid") string userid) {
this.session = session;
this.userid = userid;
if (websocketmap.containskey(userid)) {
websocketmap.remove(userid);
websocketmap.put(userid, this);
//加入set中
} else {
websocketmap.put(userid, this);
//加入set中
addonlinecount();
//在线数加1
}
log.info("用户连接:" + userid + ",当前在线人数为:" + getonlinecount());
try {
sendmessage("连接成功");
} catch (ioexception e) {
log.error("用户:" + userid + ",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@onclose
public void onclose() {
if (websocketmap.containskey(userid)) {
websocketmap.remove(userid);
//从set中删除
subonlinecount();
}
log.info("用户退出:" + userid + ",当前在线人数为:" + getonlinecount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@onmessage
public void onmessage(string message, session session) {
log.info("用户消息:" + userid + ",报文:" + message);
//可以群发消息
//消息保存到数据库、redis
if (! stringutils.isempty(message)) {
try {
//解析发送的报文
jsonobject jsonobject = json.parseobject(message);
} catch (exception e) {
e.printstacktrace();
}
}
}
/**
* @param session
* @param error
*/
@onerror
public void onerror(session session, throwable error) {
log.error("用户错误:" + this.userid + ",原因:" + error.getmessage());
error.printstacktrace();
}
/**
* 实现服务器主动推送
*/
public void sendmessage(string message) throws ioexception {
this.session.getbasicremote().sendtext(message);
}
/**
* 实现服务器主动推送
*/
public static void sendallmessage(string message) throws ioexception {
concurrenthashmap.keysetview<string, websocketserver> userids = websocketmap.keyset();
for (string userid : userids) {
websocketserver websocketserver = websocketmap.get(userid);
websocketserver.session.getbasicremote().sendtext(message);
system.out.println("websocket实现服务器主动推送成功userids====" + userids);
}
}
/**
* 发送自定义消息
*/
public static void sendinfo(string message, @pathparam("userid") string userid) throws ioexception {
log.info("发送消息到:" + userid + ",报文:" + message);
if (!stringutils.isempty(message) && websocketmap.containskey(userid)) {
websocketmap.get(userid).sendmessage(message);
} else {
log.error("用户" + userid + ",不在线!");
}
}
public static synchronized int getonlinecount() {
return onlinecount;
}
public static synchronized void addonlinecount() {
websocketserver.onlinecount++;
}
public static synchronized void subonlinecount() {
websocketserver.onlinecount--;
}
}
4. 写一个测试类,定时向客户端推送数据或者可以发起请求推送
package com.codese.controller;
import com.alibaba.fastjson2.jsonobject;
import com.codese.config.websocketserver;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import java.time.localdatetime;
import java.time.format.datetimeformatter;
import java.util.hashmap;
import java.util.map;
@restcontroller
@requestmapping("/money")
public class test {
//设置定时十秒一次
@scheduled(cron = "0/10 * * * * ?")
@postmapping("/send")
public string sendmessage() throws exception {
map<string,object> map = new hashmap<>();
// 获取当前日期和时间
localdatetime nowdatetime = localdatetime.now();
datetimeformatter datetimeformatter = datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss");
system.out.println(datetimeformatter.format(nowdatetime));
map.put("server_time",datetimeformatter.format(nowdatetime));
map.put("server_code","200");
map.put("server_message","这是服务器推送到客户端的消息哦!!");
jsonobject jsonobject = new jsonobject(map);
websocketserver.sendallmessage(jsonobject.tostring());
return jsonobject.tostring();
}
}
5. 启动springboot
package com.codese;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.boot.web.servlet.servletcomponentscan;
import org.springframework.scheduling.annotation.enablescheduling;
@enablescheduling //定时任务
@servletcomponentscan //websocket
@springbootapplication
public class websocketappmain {
public static void main(string[] args) {
springapplication.run(websocketappmain.class);
}
}
使用网上的测试工具试一下:http://coolaf.com/tool/chattest 或者http://www.jsons.cn/websocket/
效果如下:
二、前端代码
使用vue3和原生websocket
1、简单写一个websocket的公共类
需求:commentutil/websockettool.js
//需求:在javascript中实现websocket连接失败后3分钟内尝试重连3次的功能,你可以设置一个重连策略,
// 包括重连的间隔时间、尝试次数以及总时间限制。
/**
* @param {string} url url to connect
* @param {number} maxreconnectattempts maximum number of times
* @param {number} reconnect timeout
* @param {number} reconnecttimeout timeout
*
*/
class websocketreconnect {
constructor(url, maxreconnectattempts = 3, reconnectinterval = 20000, maxreconnecttime = 180000) {
this.url = url
this.maxreconnectattempts = maxreconnectattempts
this.reconnectinterval = reconnectinterval
this.maxreconnecttime = maxreconnecttime
this.reconnectcount = 0
this.reconnecttimeout = null
this.starttime = null
this.socket = null
this.connect()
}
//连接操作
connect() {
console.log('connecting...')
this.socket = new websocket(this.url)
//连接成功建立的回调方法
this.socket.onopen = () => {
console.log('websocket connection opened!')
this.clearreconnecttimeout()
this.reconnectcount = 0
}
//连接关闭的回调方法
this.socket.onclose = (event) => {
console.log('websocket connection closed:', event)
this.handleclose()
}
//连接发生错误的回调方法
this.socket.onerror = (error) => {
console.error('websocket connection error:', error)
this.handleclose() //重连
}
}
//断线重连操作
handleclose() {
if (this.reconnectcount < this.maxreconnectattempts && (this.starttime === null ||
date.now() - this.starttime < this.maxreconnecttime)) {
this.reconnectcount++
console.log(`正在尝试重连 (${this.reconnectcount}/${this.maxreconnectattempts})次...`)
this.reconnecttimeout = settimeout(() => {
this.connect()
}, this.reconnectinterval)
if (this.starttime === null) {
this.starttime = date.now()
}
} else {
console.log('超过最大重连次数或重连时间超时,已放弃连接!max reconnect attempts reached or exceeded max reconnect time. giving up.')
this.reconnectcount = 0 // 重置连接次数0
this.starttime = null // 重置开始时间
}
}
//清除重连定时器
clearreconnecttimeout() {
if (this.reconnecttimeout) {
cleartimeout(this.reconnecttimeout)
this.reconnecttimeout = null
}
}
//关闭连接
close() {
if (this.socket && this.socket.readystate === websocket.open) {
this.socket.close()
}
this.clearreconnecttimeout()
this.reconnectcount = 0
this.starttime = null
}
}
// websocketreconnect 类封装了websocket的连接、重连逻辑。
// maxreconnectattempts 是最大重连尝试次数。
// reconnectinterval 是每次重连尝试之间的间隔时间。
// maxreconnecttime 是总的重连时间限制,超过这个时间后不再尝试重连。
// reconnectcount 用于记录已经尝试的重连次数。
// starttime 用于记录开始重连的时间。
// connect 方法用于建立websocket连接,并设置相应的事件监听器。
// handleclose 方法在websocket连接关闭或发生错误时被调用,根据条件决定是否尝试重连。
// clearreconnecttimeout 方法用于清除之前设置的重连定时器。
// close 方法用于关闭websocket连接,并清除重连相关的状态。
// 使用示例
// const websocketreconnect = new websocketreconnect('ws://your-websocket-url')
// 当不再需要websocket连接时,可以调用close方法
// websocketreconnect.close();
export default websocketreconnect
2、在任意vue页面
<template>
<div>
<el-input v-model="textarea1" :rows="5" type="textarea" placeholder="请输入" />
</div>
</template>
<script setup>
import { ref, reactive,, onmounted, onunmounted } from 'vue'
import websocketreconnect from '@/commentutil/websockettool'
// --------------------------------------------
let textarea1 = ref('【消息】---->')
let websocket = null
//判断当前浏览器是否支持websocket
if ('websocket' in window) {
//连接websocket节点
websocket = new websocketreconnect('ws://127.0.0.1:8080' + '/dev-api/websocket/1122334455')
} else {
alert('浏览器不支持websocket')
}
//接收到消息的回调方法
websocket.socket.onmessage = function (event) {
let data = event.data
console.log('后端传递的数据:' + data)
//将后端传递的数据渲染至页面
textarea1.value = textarea1.value + data + '\n' + '【消息】---->'
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
websocket.close()
}
//关闭连接
function closewebsocket() {
websocket.close()
}
//发送消息
function send() {
websocket.socket.send({ kk: 123 })
}
//------------------------------------
</script>
<style scoped>
</style>
效果:
发表评论