netty-socketio和Socket.IO实现网页在线聊天功能

2024-09-05 23:28

本文主要是介绍netty-socketio和Socket.IO实现网页在线聊天功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.前端框架 Socket.IO

官方文档:https://socket.io/docs/v4/client-api/#iourl

Socket.IO 是一个库,它支持客户端和服务器之间的低延迟、双向和基于事件的通信。

Socket.IO连接可以通过不同的底层传输建立:

  • HTTP长轮询
  • WebSocket
  • WebTransport
    Socket.IO将自动选择最佳可用选项

优点:

  • 在WebSocket连接无法建立的情况下,连接将退回到HTTP长轮询
  • 当客户端最终断开连接时,为了不使服务器不堪重负,它会自动以指数级的后退延迟重新连接。
  • 当客户端断开连接时,报文将被自动缓冲,并在重新连接时发送。

2. java后端框架 netty-socketio

特点:

  • 支持xhr-polling transport(xhr轮询传输)
  • 支持websocket传输
  • 支持namespaces and rooms
  • 支持返回(接收数据的确认)
  • 支持SSL
  • 支持客户端存储(Memory, Redisson, Hazelcast)
  • 支持跨网络socket节点的分布式广播(Redisson, Hazelcast)
  • 支持OSGi
  • 支持Spring
  • 包含JPMS的Java模块信息。
  • 无锁和线程安全的实现
  • 通过注解进行声明式处理程序配置

3.java服务端实现

3.1 创建maven项目netty-socketio-learn

maven pom.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>netty-socketio-learn</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><hutool.version>5.8.11</hutool.version><spring.boot.version>3.3.1</spring.boot.version></properties><dependencyManagement><dependencies><!-- 统一依赖管理 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring.boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><!-- netty-socketio--><dependency><groupId>com.corundumstudio.socketio</groupId><artifactId>netty-socketio</artifactId><version>2.0.11</version></dependency><!-- hutool-all--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version></dependency><!-- Web 相关 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><!-- 使用 huawei / aliyun 的 Maven 源,提升下载速度 --><repositories><repository><id>huaweicloud</id><name>huawei</name><url>https://mirrors.huaweicloud.com/repository/maven/</url></repository><repository><id>aliyunmaven</id><name>aliyun</name><url>https://maven.aliyun.com/repository/public</url></repository><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><releases><enabled>false</enabled></releases></repository></repositories></project>

3.2 ChatServer实现

package cn.netty.socketio.learn;import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import com.corundumstudio.socketio.*;
import com.corundumstudio.socketio.store.MemoryStoreFactory;
import com.corundumstudio.socketio.store.StoreFactory;import java.util.concurrent.atomic.AtomicInteger;/*** ChatServer*/
public class ChatServer {private static final AtomicInteger USER_NUMBER = new AtomicInteger();/*** host name*/private static final String HOST_NAME = "localhost";/*** port*/private static final int PORT = 9093;private static final String USER_NAME = "userName";private static final String USER_ID = "userId";public static void main(String[] args) {Configuration config = new Configuration();config.setHostname(HOST_NAME);config.setPort(PORT);// client 存储工厂StoreFactory storeFactory = new MemoryStoreFactory();config.setStoreFactory(storeFactory);// 解决对此重启服务时,netty端口被占用问题 重复使用地址config.getSocketConfig().setReuseAddress(true);// 支持在线人数config.setWorkerThreads(100);// tcpNoDelay (boolean):// 如果设置为true,则禁用Nagle算法,这可以减少小数据包的延迟。// 基本原理:Nagle算法试图将多个小的数据包合并成一个较大的数据包再发送出去,这样可以减少网络中的数据包数量,// 从而提高带宽利用率。当应用发送少量数据时,TCP并不会立即将这些数据发送出去,而是等待一段时间(比如等待应用发送更多的数据),直到数据量达到一定阈值或超时后再一起发送// tcpSendBufferSize (int):// 设置发送缓冲区大小。如果设置为-1,则使用系统默认值。// tcpReceiveBufferSize (int):// 设置接收缓冲区大小。如果设置为-1,则使用系统默认值。// tcpKeepAlive (boolean):// 如果设置为true,则启用TCP的保活机制,可以在长时间没有数据传输后检测连接是否仍然有效。// soLinger (int):// 设置关闭连接前等待未发送完的数据的时间。如果是-1,则立即关闭连接而不等待。// reuseAddress (boolean):// 如果设置为true,则允许重用地址和端口,即使之前绑定过这个端口也行。// acceptBackLog (int):// 设置监听队列长度,即内核为该socket保留的已完成三次握手但尚未被accept()接受的连接的最大数目。final SocketIOServer server = new SocketIOServer(config);// 设置命名空间 前端socket连接地址:http://localhost:9093/chatSocketIONamespace socketIONamespace = server.addNamespace("/chat");// token验证socketIONamespace.addAuthTokenListener((authToken, client) -> {// 根据token获取用户信息System.out.println("token:" + authToken);Integer userId = USER_NUMBER.incrementAndGet();// 设置用户信息client.set(USER_ID, userId);String userName = getUserName(userId);client.set(USER_NAME, userName);System.out.println(StrUtil.format("token:{},用户:{} 验证成功!", authToken, userName));return AuthTokenResult.AuthTokenResultSuccess;});// 创建链接socketIONamespace.addConnectListener(client -> {String userName = client.get(USER_NAME);System.out.println(StrUtil.format("用户:{} 连接成功!", userName));});// 用户信息socketIONamespace.addEventListener("user", Object.class, (client, data, ackSender) -> {String userName = client.get(USER_NAME);// 返回用户昵称ackSender.sendAckData(userName);});// 消息事件处理socketIONamespace.addEventListener("message", Object.class, (client, data, ackSender) ->Opt.ofEmptyAble(socketIONamespace.getAllClients()).ifPresent(clients -> {// 发送消息给所有用户socketIONamespace.getBroadcastOperations().sendEvent("message", data);}));// 用户主动退出处理socketIONamespace.addDisconnectListener(client -> {String userName = client.get(USER_NAME);System.out.println(StrUtil.format("用户:{} 断开连接!", userName));});server.start();}/*** 获取用户名称** @param userId* @return*/private static String getUserName(Integer userId) {Assert.notNull(userId);return "用户" + userId;}
}

4. vue3客户端实现

使用Vue 3和socket.io-client来实现一个网页在线聊天应用:
vue3安装教程:https://socket.io/docs/v4/client-installation/

4.1 核心代码Chat.vue

<template><div><h1>在线聊天室</h1><ul><li v-for="message in messages" :key="message.id">{{ message.nickName }}: {{ message.text }}</li></ul><input v-model="newMessage" @keyup.enter="sendMessage"><button @click="sendMessage">发送</button></div>
</template><script setup>
import {ref, onMounted} from 'vue';
import {Manager} from "socket.io-client";
// 连接地址
const URL = process.env.NODE_ENV === "production" ? undefined : "http://localhost:9093";
// 如果管理器初始化时autoConnect设置为false,则启动新的连接尝试。
const manager = new Manager(URL, { autoConnect: true });
const socket = manager.socket("/chat", { auth: { token: "123" } });// 数据绑定
const messages = ref([]);
const newMessage = ref('');
const nickName = ref('');// 初始化 Socket.IO 连接
onMounted(() => {// 连接成功事件socket.on('connect', () => {console.log('Connected to the server');socket.emit('user', nickName.value, (response) => {nickName.value = response;});});// 接收消息事件socket.on('message', (msg) => {messages.value.push(msg);});// 断开连接事件socket.on('disconnect', () => {console.log('Disconnected from the server');});
});// 发送消息方法
const sendMessage = () => {if (newMessage.value.trim() !== '') {socket.emit('message', {text: newMessage.value, id: Date.now(), nickName: nickName.value});newMessage.value = '';}
};
</script><style scoped>
ul {list-style-type: none;padding: 0;
}li {margin-bottom: 5px;
}input[type="text"] {padding: 5px;margin-right: 5px;
}button {padding: 5px 10px;
}
</style>

5.运行效果

浏览器1:
在这里插入图片描述
浏览器2:
在这里插入图片描述

6.spring boot3和netty-socketio整合

6.1 application.yaml配置

server:port: 8089spring:application:name: chat-servermain:allow-circular-references: true # 允许循环依赖,因为项目是三层架构,无法避免这个情况。# Servlet 配置servlet:# 文件上传相关配置项multipart:max-file-size: 16MB # 单个文件大小max-request-size: 32MB # 设置总上传的文件大小# Jackson 配置项jackson:serialization:write-dates-as-timestamps: true # 设置 Date 的格式,使用时间戳write-date-timestamps-as-nanoseconds: false # 设置不使用 nanoseconds 的格式。例如说 1611460870.401,而是直接 1611460870401write-durations-as-timestamps: true # 设置 Duration 的格式,使用时间戳fail-on-empty-beans: false # 允许序列化无属性的 Beandebug: false

6.2 ChatSocketIOServer.java

package cn.netty.socketio.learn;import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import com.corundumstudio.socketio.*;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.corundumstudio.socketio.store.MemoryStoreFactory;
import com.corundumstudio.socketio.store.StoreFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicInteger;/*** ChatSocketIOServer* spring boot 应用启动后立即执行一些初始化任务*/
@Component
public class ChatSocketIOServer implements CommandLineRunner {private final SocketIOServer server;private final SocketIONamespace socketIONamespace;public ChatSocketIOServer() {// 创建 SocketIOServerserver = new SocketIOServer(buildConfig());// 创建 socketIONamespacesocketIONamespace = server.addNamespace("/chat");}@Beanpublic EventHandler eventHandler() {return new EventHandler(socketIONamespace);}private static final AtomicInteger USER_NUMBER = new AtomicInteger();/*** host name*/private static final String HOST_NAME = "localhost";/*** port*/private static final int PORT = 9093;private static final String USER_NAME = "userName";private static final String USER_ID = "userId";public Configuration buildConfig() {Configuration config = new Configuration();config.setHostname(HOST_NAME);config.setPort(PORT);// client 存储工厂StoreFactory storeFactory = new MemoryStoreFactory();config.setStoreFactory(storeFactory);// 解决对此重启服务时,netty端口被占用问题 重复使用地址config.getSocketConfig().setReuseAddress(true);// 支持在线人数config.setWorkerThreads(100);// tcpNoDelay (boolean):// 如果设置为true,则禁用Nagle算法,这可以减少小数据包的延迟。// 基本原理:Nagle算法试图将多个小的数据包合并成一个较大的数据包再发送出去,这样可以减少网络中的数据包数量,// 从而提高带宽利用率。当应用发送少量数据时,TCP并不会立即将这些数据发送出去,而是等待一段时间(比如等待应用发送更多的数据),直到数据量达到一定阈值或超时后再一起发送// tcpSendBufferSize (int):// 设置发送缓冲区大小。如果设置为-1,则使用系统默认值。// tcpReceiveBufferSize (int):// 设置接收缓冲区大小。如果设置为-1,则使用系统默认值。// tcpKeepAlive (boolean):// 如果设置为true,则启用TCP的保活机制,可以在长时间没有数据传输后检测连接是否仍然有效。// soLinger (int):// 设置关闭连接前等待未发送完的数据的时间。如果是-1,则立即关闭连接而不等待。// reuseAddress (boolean):// 如果设置为true,则允许重用地址和端口,即使之前绑定过这个端口也行。// acceptBackLog (int):// 设置监听队列长度,即内核为该socket保留的已完成三次握手但尚未被accept()接受的连接的最大数目。// ssl// config.setKeyStorePassword("test1234");// InputStream stream = ChatSocketIOServer.class.getResourceAsStream("/keystore.jks");// config.setKeyStore(stream);return config;}/*** EventHandler*/public static class EventHandler {private final SocketIONamespace socketIONamespace;public EventHandler(SocketIONamespace socketIONamespace) {this.socketIONamespace = socketIONamespace;}@OnConnectpublic void onConnect(SocketIOClient client) {String userName = client.get(USER_NAME);System.out.println(StrUtil.format("用户:{} 连接成功!", userName));}@OnDisconnectpublic void onDisconnect(SocketIOClient client) {String userName = client.get(USER_NAME);System.out.println(StrUtil.format("用户:{} 断开连接!", userName));}@OnEvent("user")public void onEventUser(SocketIOClient client, Object data, AckRequest ackSender) {String userName = client.get(USER_NAME);// 返回用户昵称ackSender.sendAckData(userName);}@OnEvent("message")public void onEventMessage(SocketIOClient client, Object data, AckRequest ackSender) {Opt.ofEmptyAble(socketIONamespace.getAllClients()).ifPresent(clients -> {// 发送消息给所有用户socketIONamespace.getBroadcastOperations().sendEvent("message", data);});}}@Overridepublic void run(String... args) throws Exception {// token验证socketIONamespace.addAuthTokenListener((authToken, client) -> {Integer userId = USER_NUMBER.incrementAndGet();// 设置用户信息client.set(USER_ID, userId);String userName = getUserName(userId);client.set(USER_NAME, userName);System.out.println(StrUtil.format("token:{},用户:{} 验证成功!", authToken, userName));return AuthTokenResult.AuthTokenResultSuccess;});socketIONamespace.addListeners(eventHandler());server.start();}/*** 获取用户名称** @param userId* @return*/private String getUserName(Integer userId) {Assert.notNull(userId);return "用户" + userId;}
}

6.3 ChatServerApplication.java

package cn.netty.socketio.learn;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** ChatServerApplication*/
@SpringBootApplication
public class ChatServerApplication {public static void main(String[] args) {SpringApplication.run(ChatServerApplication.class, args);}
}

启动ChatServerApplication效果和ChatServer一样

这篇关于netty-socketio和Socket.IO实现网页在线聊天功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1140362

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too