# Gsocket **Repository Path**: yukoyu/gsocket ## Basic Information - **Project Name**: Gsocket - **Description**: 封装套接字(socket) - **Primary Language**: Unknown - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 1 - **Created**: 2024-03-15 - **Last Updated**: 2024-07-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Gsocket #### 介绍 Gsocket提供了灵活、可扩展的网络服务器框架,支持同时处理UDP、TCP和域套接字(Domain Socket)通信。该框架采用了面向对象的设计理念,利用模板和回调机制实现通用性和可定制性的平衡。 #### 工作流程 1. **服务器初始化**: - 创建相应类型的服务器实例(UDP、TCP、域套接字)。 - 设置必要的回调函数处理消息接收、连接建立和关闭等事件。 2. **服务器绑定和启动**: - 调用 `Bind` 方法绑定服务器到指定的端口或路径。 - 对于TCP服务器,调用 `Listen` 开始监听客户端连接。 3. **事件处理**: - 根据接收到的消息类型,在相应的回调函数中处理消息内容,并根据业务逻辑进行回复或者其他操作。 4. **关闭服务器**: - 调用 `Close` 方法关闭服务器,释放资源并停止监听。 #### 安装教程 ``` git clone https://gitee.com/yukoyu/g-tlv.git ``` ``` ./gsocket/async-sockets/install.sh ``` #### 使用说明 ##### UDP ``` { //建立UDP UDPServer<> udpServer; //设置接收消息回调函数 udpServer.onRawMessageReceived = [&](const char* message, int length, string ipv4, uint16_t port) { //接收到的消息 cout << ipv4 << ":" << port << " => " << message << "(" << length << ")" << endl; udpServer.SendTo(message, length, ipv4, port); }; //绑定端口 udpServer.Bind(8888); //执行任务 //udpServer.SendTo("Hi", 3, "192.168.8.2", 6688); //关闭UDP udpServer.Close(); } ``` ##### TCP ``` { //建立TCP TCPServer<> tcpServer; tcpServer.onNewConnection = [&](TCPSocket<> *newClient) { //监听到客户端的连接 cout << "New client: ["; cout << newClient->remoteAddress() << ":" << newClient->remotePort() << "]" << endl; //设置接收消息回调函数 newClient->onMessageReceived = [newClient](string message) { //接收到的消息 cout << newClient->remoteAddress() << ":" << newClient->remotePort() << " => " << message << endl; //回复消息 newClient->Send("OK!"); }; //设置断开连接回调函数 newClient->onSocketClosed = [newClient](int errorCode) { cout << "Socket closed:" << newClient->remoteAddress() << ":" << newClient->remotePort() << " -> " << errorCode << endl; cout << flush; }; }; tcpServer.Bind(8888); tcpServer.Listen(); //执行其他任务 tcpServer.Close(); } ``` ##### 域套接字Domain ``` { constexpr const char* path = "./localhostDomain"; //建立Domain DgramDomainServer<> domainServer; //设置接收消息回调函数 domainServer.onRawMessageReceived = [&](const char* message, int length, string path) { cout << path << " => " << message << "(" << length << ")" << endl; udpServer.SendTo(message, length, path); }; //绑定本地 domainServer.Bind(path); //执行任务 //domainServer.SendTo("Hi", 3, path); //关闭Domain domainServer.Close(); } ``` #### 备注 | 序号 | 功能 | 备注 | | ---- | ------- | ------ | | 1 | UDP | 支持 | | 2 | TCP | 支持 | | 3 | Domain | 支持 | | 4 | UDP多播 | 支持 | | 5 | UDP广播 | 待开发 | | 6 | I\O复用 | 待开发 | | | | | #### 帮助 请联系邮箱:[ggvyyy@163.com](mailto:ggvyyy@163.com)