Skip to content

High-Performance-Java/FastSocket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastSocket Logo

FastSocket

简单而强大的 Java Socket 编程封装库

Java Version Maven License JUnit

📖 简介

FastSocket 是一个轻量级、高性能的 Java Socket 编程封装库,旨在简化传统 Socket 开发的复杂性。它提供了简洁的 API、灵活的编解码器、自动重连机制、心跳检测等功能,让开发者能够专注于业务逻辑而非底层网络细节。

✨ 核心特性

  • 🚀 简洁易用: 通过 FastSocket.server()FastSocket.client() 快速创建服务端和客户端
  • 🔧 灵活编解码: 内置长度字段和分隔符编解码器,支持自定义协议实现
  • 🔄 自动重连: 提供固定间隔和指数退避两种重连策略
  • 💓 心跳检测: 内置心跳机制,自动检测连接健康状态
  • 🔒 SSL/TLS 支持: 提供安全的加密通信支持
  • 🎯 配置丰富: 通过 Builder 模式灵活配置超时、缓冲区、空闲检测等参数
  • 🧩 事件驱动: 基于监听器模式的连接管理和消息处理
  • ♻️ 资源管理: 支持 try-with-resources 自动释放资源

🚀 快速开始

前置要求

  • Java 26+
  • Maven 3.8+

安装依赖

<dependency>
    <groupId>com.fastsocket</groupId>
    <artifactId>fastsocket</artifactId>
    <version>1.0.0</version>
</dependency>

基础示例

创建服务端

import com.fastsocket.core.FastSocket;
import com.fastsocket.config.SocketConfig;
import com.fastsocket.handler.ConnectionListener;

// 使用 try-with-resources 自动管理资源
try (var server = FastSocket.server(
    SocketConfig.builder()
        .port(9000)
        .bufferSize(8192)
        .build()
)) {
    // 添加连接监听器
    server.addListener(new ConnectionListener() {
        @Override
        public void onConnected(FastConnection connection) {
            System.out.println("新连接: " + connection.getId());
        }

        @Override
        public void onMessage(FastConnection connection, byte[] data) {
            String message = new String(data);
            System.out.println("收到消息: " + message);
            
            // 回复消息
            connection.send(("回应: " + message).getBytes());
        }

        @Override
        public void onDisconnected(FastConnection connection) {
            System.out.println("连接断开: " + connection.getId());
        }
    });

    // 启动服务端
    server.start();
    System.out.println("服务端已启动,监听端口: 9000");
}

创建客户端

import com.fastsocket.core.FastSocket;
import com.fastsocket.config.SocketConfig;
import com.fastsocket.handler.ConnectionListener;

// 使用 try-with-resources 自动管理资源
try (var client = FastSocket.client(
    SocketConfig.builder()
        .host("localhost")
        .port(9000)
        .autoReconnect(true)
        .heartbeatInterval(30000)  // 每30秒发送心跳
        .build()
)) {
    // 添加连接监听器
    client.addListener(new ConnectionListener() {
        @Override
        public void onConnected(FastConnection connection) {
            System.out.println("已连接到服务端");
            
            // 发送消息
            connection.send("Hello, FastSocket!".getBytes());
        }

        @Override
        public void onMessage(FastConnection connection, byte[] data) {
            String response = new String(data);
            System.out.println("收到响应: " + response);
        }

        @Override
        public void onDisconnected(FastConnection connection) {
            System.out.println("与服务端断开连接");
        }
    });

    // 连接到服务端
    client.connect();
    
    // 保持运行
    Thread.sleep(60000);
}

高级功能

自定义编解码器

import com.fastsocket.codec.MessageCodec;

public class JsonCodec implements MessageCodec {
    @Override
    public void encode(DataOutputStream out, byte[] data) throws IOException {
        // JSON 格式编码逻辑
        int length = data.length;
        out.writeInt(length);
        out.write(data);
    }

    @Override
    public byte[] decode(DataInputStream in) throws IOException {
        // JSON 格式解码逻辑
        int length = in.readInt();
        byte[] data = new byte[length];
        in.readFully(data);
        return data;
    }
}

// 使用自定义编解码器
var server = FastSocket.server(config, new JsonCodec());
var client = FastSocket.client(config, new JsonCodec());

配置重连策略

import com.fastsocket.reconnect.ExponentialBackoffStrategy;

// 指数退避重连策略:初始延迟1秒,最大延迟60秒,最多重试10次
var strategy = new ExponentialBackoffStrategy(1000, 60000, 10);

var client = FastSocket.client(
    SocketConfig.builder()
        .host("localhost")
        .port(9000)
        .autoReconnect(true)
        .reconnectStrategy(strategy)
        .build()
);

SSL/TLS 加密通信

import com.fastsocket.ssl.FastSslServer;
import com.fastsocket.ssl.FastSslClient;
import com.fastsocket.ssl.SslConfig;

// SSL 服务端配置
var sslConfig = SslConfig.builder()
    .keyStorePath("server.keystore")
    .keyStorePassword("password")
    .trustStorePath("server.truststore")
    .trustStorePassword("password")
    .build();

try (var server = FastSslServer.server(config, sslConfig)) {
    server.start();
}

// SSL 客户端配置
var clientSslConfig = SslConfig.builder()
    .trustStorePath("client.truststore")
    .trustStorePassword("password")
    .build();

try (var client = FastSslClient.client(config, clientSslConfig)) {
    client.connect();
}

📦 模块结构

com.fastsocket
├── codec/              # 编解码器
│   ├── MessageCodec           # 编解码接口
│   ├── LengthFieldCodec       # 长度字段编解码器
│   └── DelimiterCodec         # 分隔符编解码器
├── config/             # 配置类
│   └── SocketConfig           # Socket 配置(Builder 模式)
├── core/               # 核心类
│   ├── FastSocket             # 入口类(工厂方法)
│   ├── FastServer             # 服务端实现
│   ├── FastClient             # 客户端实现
│   └── FastConnection         # 连接抽象
├── handler/            # 处理器
│   ├── ConnectionListener     # 连接监听器
│   ├── HeartbeatListener      # 心跳监听器
│   ├── ClientHeartbeatListener
│   └── ServerHeartbeatListener
├── reconnect/          # 重连策略
│   ├── ReconnectStrategy      # 重连策略接口
│   ├── FixedReconnectStrategy # 固定间隔重连
│   └── ExponentialBackoffStrategy # 指数退避重连
├── ssl/                # SSL/TLS 支持
│   ├── SslConfig              # SSL 配置
│   ├── FastSslServer          # SSL 服务端
│   └── FastSslClient          # SSL 客户端
└── exception/          # 异常类
    ├── FastSocketException    # 基础异常
    └── ConnectionException    # 连接异常

⚙️ 配置说明

SocketConfig 参数

参数 类型 默认值 说明
host String "localhost" 服务端地址
port int 8080 端口号
soTimeout int 0 Socket 读取超时(ms),0 表示无限
bufferSize int 4096 缓冲区大小
autoReconnect boolean false 客户端自动重连
reconnectStrategy ReconnectStrategy FixedReconnectStrategy 重连策略
heartbeatInterval int 0 心跳发送间隔(ms),0 表示不发送
heartbeatTimeout int 30000 心跳超时时间(ms)
idleTimeout int 0 空闲超时(ms),0 表示不限

重连策略

FixedReconnectStrategy: 固定间隔重连

new FixedReconnectStrategy(5000, -1);  // 每5秒重连,无限次

ExponentialBackoffStrategy: 指数退避重连

new ExponentialBackoffStrategy(1000, 60000, 10);  
// 初始1秒,最大60秒,最多10次

🧪 测试

运行单元测试:

mvn test

生成测试报告:

mvn surefire-report:report

📝 设计理念

1. 简化 API

通过静态工厂方法和 Builder 模式,将复杂的 Socket 配置和使用简化为几行代码。

2. 职责分离

  • 编解码层: 处理 TCP 粘包/拆包问题
  • 配置层: 集中管理所有配置参数
  • 核心层: 实现 Socket 通信逻辑
  • 处理器层: 事件驱动的回调机制
  • 策略层: 可插拔的重连策略

3. 资源安全

所有核心类都实现了 AutoCloseable 接口,支持 try-with-resources 自动释放资源,避免内存泄漏。

4. 可扩展性

  • 通过实现 MessageCodec 接口自定义协议
  • 通过实现 ReconnectStrategy 接口自定义重连逻辑
  • 通过 ConnectionListener 监听各种连接事件

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages