百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

springboot2.2.X手册:5分钟用Netty搭建高性能异步WebSocket服务

yuyutoo 2024-10-12 01:40 6 浏览 0 评论

溪云阁:专注编程教学,架构,JAVA,Python,微服务,机器学习等领域,欢迎关注,一起学习。

断更快两个月了,6月份工作忙到飞起,7月份家里又有事,已经累到躺下就想睡觉的程度了。

现在我们做WebSocket服务,很多时候都是会整合Netty作为服务器,但是有个问题,就是发现网上的整合起来,比较繁琐,各种配置,各种对应,最关键是千篇一律的网文,看得好辛苦了,今天咱们来介绍一个开源的组件,帮你快速搭建基于Netty的WebSocket服务,让你更加轻松,更加专注于业务开发。

组件介绍

netty-websocket-spring-boot-starter是基于Netty服务器来做的WebSocket服务器,不需要配置Netty服务器信息,只需要配置Webscoket的注解就行,目前用起来还是很方便的。

加载包体

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.boots</groupId>
        <artifactId>boots</artifactId>
        <version>1.1.0.RELEASE</version>
    </parent>
    <groupId>boots.weboscket</groupId>
    <artifactId>boots-weboscket</artifactId>
    <version>2.0.0.RELEASE</version>
    <name>boots-weboscket</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>

        <!-- 公共组件:swagger服务+入参出参+统一异常拦截 -->
        <dependency>
            <groupId>com.boots</groupId>
            <artifactId>module-boots-api</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>


        <!-- netty工具类 -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
        </dependency>

        <!-- netty-websocket整合工具类 -->
        <dependency>
            <groupId>org.yeauty</groupId>
            <artifactId>netty-websocket-spring-boot-starter</artifactId>
            <version>0.9.5</version>
        </dependency>


    </dependencies>
</project>


配置文件

######配置基本信息######
##配置应用名称
spring.application.name: boots-websocket
##配置时间格式,为了避免精度丢失,全部换成字符串
spring.jackson.timeZone: GMT+8
spring.jackson.dateFormat: yyyy-MM-dd HH:mm:ss
spring.jackson.generator.writeNumbersAsStrings: true

单个推送后端代码

/**
 * All rights Reserved, Designed By 林溪
 * Copyright:    Copyright(C) 2016-2020
 * Company       溪云阁 .
 */

package com.boots.websocket.websocket;

import org.yeauty.annotation.OnClose;
import org.yeauty.annotation.OnError;
import org.yeauty.annotation.OnMessage;
import org.yeauty.annotation.OnOpen;
import org.yeauty.annotation.ServerEndpoint;
import org.yeauty.pojo.Session;

import com.module.boots.exception.CommonRuntimeException;

import io.netty.handler.codec.http.HttpHeaders;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 单个推送服务
 * @author:溪云阁
 * @date:2020年8月4日
 */
@Slf4j
@ServerEndpoint(path = "/SingleSocket", host = "127.0.0.1", port = "8900")
public class SingleSocket {

    /**
     * 新建WebSocket的时候,执行该方法
     * @author 溪云阁
     * @param session
     * @param headers void
     */
    @OnOpen
    @SneakyThrows(CommonRuntimeException.class)
    public void onOpen(Session session, HttpHeaders headers) {
        log.info("WebSocket服务连接成功");
    }

    /**
     * 关闭WebSocket的时候,执行该方法
     * @author 溪云阁
     * @param session void
     */
    @OnClose
    @SneakyThrows(CommonRuntimeException.class)
    public void onClose(Session session) {
        log.info("WebSocket服务关闭成功");
    }

    /**
     * WebSocket发生异常的时候,执行该方法
     * @author 溪云阁
     * @param session
     * @param th void
     */
    @OnError
    public void onError(Session session, Throwable th) {
        log.error("{}", th.fillInStackTrace());
        th.printStackTrace();
    }

    /**
     * WebSocket接收到的消息为字符串的时候,指定该方法
     * @author 溪云阁
     * @param session
     * @param msg void
     */
    @OnMessage
    @SneakyThrows(CommonRuntimeException.class)
    public void OnMessage(Session session, String msg) {
        log.info("接收到的信息:{}", msg);
        session.sendText(msg);
    }

}

单个推送前端页面

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>单个推送</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="/layui/css/layui.css" media="all">
</head>
<body>

	<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px; margin-left: 310px; margin-right: 310px">
		<legend>输出内容</legend>
	</fieldset>

	<form class="layui-form" action="" style="margin-left: 200px; margin-right: 310px">
		<div class="layui-form-item layui-form-text">
			<div class="layui-input-block">
				<textarea placeholder="请输入内容" class="layui-textarea" rows="20" id="contentArea"></textarea>
			</div>
		</div>
	</form>

	<form class="layui-form layui-form-pane" style="margin-left: 310px; margin-right: 310px" action="">
		<div class="layui-form-item">
			<label class="layui-form-label">输入</label>
			<div class="layui-input-block">
				<input type="text" name="content" id="content" autocomplete="off" placeholder="请输入内容" class="layui-input">
			</div>
		</div>
	</form>
	<div class="layui-form-item" style="margin-left: 310px; margin-right: 310px">
		<button class="layui-btn" onclick="sendMsg()">发送</button>
	</div>

	<script src="/js/jquery.min.js" ></script>
	<script src="/layui/layui.js" charset="utf-8"></script>
	<script>
		var websocket = new WebSocket("ws://127.0.0.1:8900/SingleSocket");
		//WebSocket打开
		websocket.onopen = function(evt) {
			$('#contentArea').html("WebSocket服务连接成功");
		};

		//WebSocket推送
		websocket.onmessage = function(evt) {
			var val = $('#contentArea').val() + "
";
			$('#contentArea').html(val + evt.data);
		};

		//WebSocket关闭
		websocket.onclose = function(evt) {
			$('#contentArea').html("WebSocket服务关闭成功");
		};

		function sendMsg() {
			var text = $('#content').val();
			websocket.send(text);
		}
	</script>

</body>
</html>

群发推送后端代码

/**
 * All rights Reserved, Designed By 林溪
 * Copyright:    Copyright(C) 2016-2020
 * Company       溪云阁 .
 */

package com.boots.websocket.websocket;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.yeauty.annotation.OnClose;
import org.yeauty.annotation.OnError;
import org.yeauty.annotation.OnMessage;
import org.yeauty.annotation.OnOpen;
import org.yeauty.annotation.ServerEndpoint;
import org.yeauty.pojo.Session;

import com.module.boots.exception.CommonRuntimeException;

import io.netty.handler.codec.http.HttpHeaders;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 群组推送服务
 * @author:溪云阁
 * @date:2020年8月4日
 */
@Slf4j
@ServerEndpoint(path = "/groupSocket", host = "127.0.0.1", port = "8901")
public class GroupSocket {

    // 定义存放Session的缓存对象
    private Map<String, Session> map = new ConcurrentHashMap<>();

    /**
     * 新建WebSocket的时候,执行该方法
     * @author 溪云阁
     * @param session
     * @param headers void
     */
    @OnOpen
    @SneakyThrows(CommonRuntimeException.class)
    public void onOpen(Session session, HttpHeaders headers) {
        // 把Session放到缓存中,后面群发使用
        map.put(session.id().toString(), session);
        log.info("WebSocket服务连接成功");
    }

    /**
     * 关闭WebSocket的时候,执行该方法
     * @author 溪云阁
     * @param session void
     */
    @OnClose
    @SneakyThrows(CommonRuntimeException.class)
    public void onClose(Session session) {
        // 当关闭的时候,删除缓存中的session
        if (map.containsKey(session.id().toString())) {
            map.remove(session.id().toString());
        }
        log.info("WebSocket服务关闭成功");
    }

    /**
     * WebSocket发生异常的时候,执行该方法
     * @author 溪云阁
     * @param session
     * @param th void
     */
    @OnError
    public void onError(Session session, Throwable th) {
        log.error("{}", th.fillInStackTrace());
        th.printStackTrace();
    }

    /**
     * WebSocket接收到的消息为字符串的时候,指定该方法
     * @author 溪云阁
     * @param session
     * @param msg void
     */
    @OnMessage
    @SneakyThrows(CommonRuntimeException.class)
    public void OnMessage(String msg) {
        map.forEach((key, session) -> {
            log.info("接收到的信息:{}", msg);
            session.sendText(msg);
        });

    }

}



群发推送前端页面

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>群发推送</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="/layui/css/layui.css" media="all">
</head>
<body>

	<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px; margin-left: 310px; margin-right: 310px">
		<legend>输出内容</legend>
	</fieldset>

	<form class="layui-form" action="" style="margin-left: 200px; margin-right: 310px">
		<div class="layui-form-item layui-form-text">
			<div class="layui-input-block">
				<textarea placeholder="请输入内容" class="layui-textarea" rows="10" id="contentArea1"></textarea>
			</div>
		</div>
	</form>
	
	<form class="layui-form" action="" style="margin-left: 200px; margin-right: 310px">
		<div class="layui-form-item layui-form-text">
			<div class="layui-input-block">
				<textarea placeholder="请输入内容" class="layui-textarea" rows="10" id="contentArea2"></textarea>
			</div>
		</div>
	</form>

	<form class="layui-form layui-form-pane" style="margin-left: 310px; margin-right: 310px" action="">
		<div class="layui-form-item">
			<label class="layui-form-label">输入</label>
			<div class="layui-input-block">
				<input type="text" name="content" id="content" autocomplete="off" placeholder="请输入内容" class="layui-input">
			</div>
		</div>
	</form>
	<div class="layui-form-item" style="margin-left: 310px; margin-right: 310px">
		<button class="layui-btn" onclick="sendMsg()">发送</button>
	</div>

	<script src="/js/jquery.min.js" ></script>
	<script src="/layui/layui.js" charset="utf-8"></script>
	<script>
		var websocket1 = new WebSocket("ws://127.0.0.1:8901/groupSocket");
		var websocket2 = new WebSocket("ws://127.0.0.1:8901/groupSocket");
		//第一个WebSocket打开
		websocket1.onopen = function(evt) {
			$('#contentArea1').html("第一个WebSocket服务连接成功");
		};

		//第一个WebSocket推送
		websocket1.onmessage = function(evt) {
			var val = $('#contentArea1').val() + "
";
			$('#contentArea1').html(val + evt.data);
		};

		//第一个WebSocket关闭
		websocket1.onclose = function(evt) {
			$('#contentArea1').html("第一个WebSocket服务关闭成功");
		};
		
		//第二个WebSocket打开
		websocket2.onopen = function(evt) {
			$('#contentArea2').html("第二个WebSocket服务连接成功");
		};

		//第二个WebSocket推送
		websocket2.onmessage = function(evt) {
			var val = $('#contentArea2').val() + "
";
			$('#contentArea2').html(val + evt.data);
		};

		//第二个WebSocket关闭
		websocket2.onclose = function(evt) {
			$('#contentArea2').html("第二个WebSocket服务关闭成功");
		};

		function sendMsg() {
			var text = $('#content').val();
			websocket1.send(text);
			websocket2.send(text);
		}
	</script>

</body>
</html>

启动类

package com.boots.websocket;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * 服务启动类
 * @author:溪云阁
 * @date:2020年5月2日
 */
@SpringBootApplication
@ComponentScan(basePackages = { "com.module", "com.boots" })
public class BootsWebSocketApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootsWebSocketApplication.class, args);
    }

}

单个推送测试


群发推送测试


总结及拓展

相比于需要自己整合Netty的配置,目前用起来还是很方便的,Netty的配置可以在注解类ServerEndpoint看到,里面一进去就会发现还是很清楚的。

目前发现有个不足的,就是超过一定时间不连接的时候,就会自动断开,不过这个可以在前端做个超时设置或者心跳检测,就可以了,问题不大,用起来还是很爽的。



--END--

作者:@溪云阁

原创作品,抄袭必究

如需要源码,转发,关注后私信我

部分图片或代码来源网络,如侵权请联系删除,谢谢!

历史文章

springboot2.2.X手册:抛弃ELK,百亿日志+调用链的Easylog很放心

springboot2.2.X手册:Eureka不更,Consul被禁,启用Nacos

springboot2.2.X手册:构建全局唯一的短链接数据中心

springboot2.2.X手册:放弃fastdfs,整合Minio做文件服务器真香

springboot2.2.X手册:分布式系统下,重复提交的解决方案

springboot2.2.X手册:Easypoi导出excel,最新版的手感香不香?

springboot2.2.X手册:项目从100M瘦身到100K,部署省事多了!

springboot2.2.X手册:redis的7种类型100个方法全解析

springboot2.2.X手册:是时候用Lettuce替换Jedis操作Redis缓存了

springboot2.2.X手册:构建多元化的API接口,我们这样子设计

springboot2.2.X手册:基于Jasypt的JavaConfig方式敏感信息加密

springboot2.2.X手册:整合最新版MybatisPlus 3.3.1版本

springboot2.2.X手册:对象复制哪种最快?7种复制方式性能对比

springboot2.2.X手册:基于OSS解决文件存储(一年9元^^,赚了)

springboot2.2.X手册:36个注解详细解析,一目了然

相关推荐

野路子科技!2步教你把手机改造成一个FTP服务器,支持PC互传

哈喽,大家好,我是野路子科技,今天来给大家带来一个教程,希望大家喜欢。正如标题所言,就是教大家如何把售价改造成FTP服务器,而这个时候估计有朋友会问了,把手机改造成FTP服务器有什么用呢?现在有Q...

不得不看:别样于Server-U的群晖文件存储服务器的搭建与使用

我先前的作品中,有着关于Server-U的ftp文件存储服务器的搭建与访问的头条文章和西瓜视频,而且我们通过各种方式也给各位粉丝介绍了如何突破局域网实现真正意义上的公网访问机制技术。关于Server-...

Qt三种方式实现FTP上传功能_qt引入qftp库

FTP协议FTP的中文名称是“文件传输协议”,是FileTransferProtocol三个英文单词的缩写。FTP协议是TCP/IP协议组中的协议之一,其传输效率非常高,在网络上传输大的文件时,经...

Filezilla文件服务器搭建及客户端的使用

FileZilla是一个免费开源的FTP软件,分为客户端版本和服务器版本,具备所有的FTP软件功能。可控性、有条理的界面和管理多站点的简化方式使得Filezilla客户端版成为一个方便高效的FTP客户...

美能达柯美/震旦复印机FTP扫描怎么设置?

好多网友不知道怎么安装美能达/震旦复印机扫描,用得最多是SMB和FTP扫描,相对于SMB来说,FTP扫描安装步骤更为便捷,不容易出问题,不需要设置文件夹共享,所以小编推荐FTP来扫描以美能达机器为例详...

CCD(简易FTP服务器软件)_简单ftp服务器软件

CCD简易FTP服务器软件是一款很方便的FPT搭建工具,可以将我们的电脑快速变成一个FPT服务器。使用方法非常简单,只要运行软件就会自动生效,下载银行有该资源。该工具是不提供操作界面的,其他用户可以输...

Ubuntu系统搭建FTP服务器教程_ubuntu架设服务器

在Ubuntu系统上搭建FTP服务器是文件传输的一个非常实用方法,适合需要进行大量文件交换的场景。以下是一步步指导,帮助您在Ubuntu上成功搭建FTP服务器。1.安装vsftpd软件...

理光FTP扫描设置教程_理光ftp扫描设置方法

此教程主要用来解决WIN10系统下不能使用SMB文件夹扫描的问题,由于旧的SMB协议存在安全漏洞,所以微软在新的系统,WIN8/WIN10/SERVER201220162018里使用了新的SMB传...

纯小白如何利用wireshark学习网络技术

写在前面工欲善其事必先利其器!熟悉掌握一种神器对以后的工作必然是有帮助的,下面我将从简单的描述Wireshark的使用和自己思考去写,若有错误或不足还请批评指正。...

京东买13盘位32GB内存NAS:NAS系统安装设置教程

本内容来源于@什么值得买APP,观点仅代表作者本人|作者:yasden你没有看错,我在京东自营商城购买硬件,组装了一台13盘位,32GB内存的NAS,硬盘有13个盘位!CPU是AMD的5500!本文...

FileZilla搭建FTP服务器图解教程_filezilla server搭建ftp服务器

...

python教程之FTP相关操作_python ftps

ftplib类库常用相关操作importftplibftp=ftplib.FTP()ftp.set_debuglevel(2)#打开调试级别2,显示详细信息ftp.connect(“I...

xftp怎么用,xftp怎么用,具体使用方法

Xftp是一款界面化的ftp传输工具,用起来方便简单,这里为大家分享下Xftp怎么使用?希望能帮到有需要的朋友。IIS7服务器管理工具可以批量管理、定时上传下载、同步操作、数据备份、到期提醒、自动更新...

树莓派文件上传和下载,详细步骤设置FTP服务器

在本指南中,详细记录了如何在树莓Pi上设置FTP。设置FTP可以在网络上轻松地将文件传输到Pi上。FTP是文件传输协议的缩写,只是一种通过网络在两个设备之间传输文件的方法。还有一种额外的方法,你可以用...

win10电脑操作系统,怎么设置FTP?windows10系统设置FTP操作方法

打印,打印,扫描的日常操作是每一个办公工作人员的必需专业技能,要应用FTP作用扫描文件到电脑上,最先要必须一台可以接受文件的FTP服务器。许多软件都需要收费标准进行,但人们还可以应用Windows的系...

取消回复欢迎 发表评论: