当前位置: 首页 > article >正文

【C++】Linux平台C++实现Socket通信(Unix域、TCP/IP、UDP)

Unix 域套接字

Unix 域套接字非常适合在同一台机器上的不同进程之间进行高效的通信。由于它们不需要网络协议栈,因此在性能上通常优于 TCP/IP 套接字。

Socket server端

StartSocketServer.cpp源代码:

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <cstring>
#include <string.h>

constexpr const char *SOCKET_PATH = "./socket"; // Unix socket 文件路径

void StartSocketServer() {
    // 创建一个 Unix 域套接字
    std::cout << "Starting Socket Server..." << std::endl;
    int serverSocketFd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (serverSocketFd == -1) {
        std::cerr << "Error creating socket" << std::endl;
        return;
    }
    std::cout << "Socket created with file descriptor: " << serverSocketFd << std::endl;

    // 绑定套接字到指定路径
    sockaddr_un serverAddr;
    serverAddr.sun_family = AF_UNIX;
    strncpy(serverAddr.sun_path, SOCKET_PATH, sizeof(serverAddr.sun_path) - 1);
    unlink(serverAddr.sun_path); // 确保路径不存在
    if (bind(serverSocketFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {
        std::cerr << "Error binding socket" << std::endl;
        close(serverSocketFd);
        return;
    }

    // 监听传入的连接
    if (listen(serverSocketFd, 5) == -1) {
        std::cerr << "Error listening for connections" << std::endl;
        close(serverSocketFd);
        return;
    }
    std::cout << "Server is listening for incoming connections..." << std::endl;

    while (true) {
        // 接受传入的连接
        std::cout << "Waiting for client connection..." << std::endl;
        int clientSocketFd = accept(serverSocketFd, nullptr, nullptr);
        if (clientSocketFd == -1) {
            std::cerr << "Error accepting connection" << std::endl;
            close(serverSocketFd);
            return;
        }
        std::cout << "Client connected, clientSocketFd: " << clientSocketFd << std::endl;

        // 接收来自客户端的数据
        char buffer[256];
        ssize_t bytesReceived = recv(clientSocketFd, buffer, sizeof(buffer) - 1, 0);
        if (bytesReceived > 0) {
            buffer[bytesReceived] = '\0'; // Null-terminate the received data
            std::cout << "Received data: " << buffer << std::endl;

            // 发送响应给客户端
            const char *response = "OK";
            send(clientSocketFd, response, strlen(response), 0);
            std::cout << "Response sent to client." << std::endl;
        } else {
            std::cerr << "Error receiving data" << std::endl;
        }

        // 关闭客户端套接字
        close(clientSocketFd);
        std::cout << "Client socket closed." << std::endl;
    }

    // 关闭服务器套接字(虽然在此代码中不会到达)
    close(serverSocketFd);
}

int main() {
    std::cout << "Hello, World!" << std::endl;
    StartSocketServer(); // 启动套接字服务器
    return 0;
}

使用g++编译生成可执行文件StartSocketServer:

g++ -o StartSocketServer StartSocketServer.cpp

启动socket server端:

./StartSocketServer

启动后socket server端打印如下:

Hello, World!
Starting Socket Server...
Socket created with file descriptor: 3
Server is listening for incoming connections...
Waiting for client connection...

Socket client端

StartSocketClient.cpp源代码:

#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <cstring>

constexpr const char *SOCKET_PATH = "./socket"; // Unix socket 文件路径

void StartSocketClient() {
    // 创建一个 Unix 域套接字
    int clientSocketFd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (clientSocketFd == -1) {
        std::cerr << "Error creating socket" << std::endl;
        return;
    }

    // 设置服务器地址结构
    sockaddr_un serverAddr;
    serverAddr.sun_family = AF_UNIX;
    strncpy(serverAddr.sun_path, SOCKET_PATH, sizeof(serverAddr.sun_path) - 1);

    // 连接到服务器
    if (connect(clientSocketFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {
        std::cerr << "Error connecting to socket" << std::endl;
        close(clientSocketFd);
        return;
    }

    std::cout << "Connected to server!" << std::endl;

    // 向服务器发送消息
    const char *message = "Message sent by client!";
    ssize_t bytesSent = send(clientSocketFd, message, strlen(message), 0);
    if (bytesSent == -1) {
        std::cerr << "Error sending message" << std::endl;
    } else {
        std::cout << "Message sent: " << message << std::endl;
    }

    // 可选:接收来自服务器的响应
    char buffer[256];
    ssize_t bytesReceived = recv(clientSocketFd, buffer, sizeof(buffer) - 1, 0);
    if (bytesReceived > 0) {
        buffer[bytesReceived] = '\0'; // Null-terminate the received data
        std::cout << "Received from server: " << buffer << std::endl;
    } else if (bytesReceived == -1) {
        std::cerr << "Error receiving data" << std::endl;
    }

    // 关闭套接字
    close(clientSocketFd);
}

int main() {
    StartSocketClient(); // 启动套接字客户端
    return 0;
}

使用g++编译生成可执行文件StartSocketClient:

g++ -o StartSocketClient StartSocketClient.cpp

启动socket client端:

./StartSocketClient 

启动后socket client端打印如下:

Connected to server!
Message sent: Message sent by client!
Received from server: OK

socket server端打印如下:

Hello, World!
Starting Socket Server...
Socket created with file descriptor: 3
Server is listening for incoming connections...
Waiting for client connection...
Client connected, clientSocketFd: 4
Received data: Message sent by client!
Response sent to client.
Client socket closed.
Waiting for client connection...

TCP/IP 套接字

TCP/IP 套接字是最常用的网络通信方式,适用于通过网络进行通信的应用程序。它使用 TCP 协议提供可靠的、面向连接的通信。

Socket server端

#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <cstring>

constexpr const char *SERVER_IP = "127.0.0.1"; // 本地回环地址
constexpr const int SERVER_PORT = 8080; // 端口号

void StartTcpServer() {
    int serverSocketFd = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocketFd == -1) {
        std::cerr << "Error creating socket" << std::endl;
        return;
    }

    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
    serverAddr.sin_port = htons(SERVER_PORT);

    if (bind(serverSocketFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {
        std::cerr << "Error binding socket" << std::endl;
        close(serverSocketFd);
        return;
    }

    if (listen(serverSocketFd, 5) == -1) {
        std::cerr << "Error listening for connections" << std::endl;
        close(serverSocketFd);
        return;
    }

    std::cout << "TCP Server is listening for incoming connections..." << std::endl;

    while (true) {
        int clientSocketFd = accept(serverSocketFd, nullptr, nullptr);
        if (clientSocketFd == -1) {
            std::cerr << "Error accepting connection" << std::endl;
            close(serverSocketFd);
            return;
        }

        char buffer[256];
        ssize_t bytesReceived = recv(clientSocketFd, buffer, sizeof(buffer) - 1, 0);
        if (bytesReceived > 0) {
            buffer[bytesReceived] = '\0';
            std::cout << "Received data: " << buffer << std::endl;
            const char *response = "OK";
            send(clientSocketFd, response, strlen(response), 0);
        }

        close(clientSocketFd);
    }

    close(serverSocketFd);
}

int main() {
    StartTcpServer();
    return 0;
}

Socket client端

#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <cstring>

constexpr const char *SERVER_IP = "127.0.0.1"; // 本地回环地址
constexpr const int SERVER_PORT = 8080; // 端口号

void StartTcpClient() {
    int clientSocketFd = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocketFd == -1) {
        std::cerr << "Error creating socket" << std::endl;
        return;
    }

    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
    serverAddr.sin_port = htons(SERVER_PORT);

    if (connect(clientSocketFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {
        std::cerr << "Error connecting to server" << std::endl;
        close(clientSocketFd);
        return;
    }

    const char *message = "Hello from TCP client!";
    send(clientSocketFd, message, strlen(message), 0);

    char buffer[256];
    ssize_t bytesReceived = recv(clientSocketFd, buffer, sizeof(buffer) - 1, 0);
    if (bytesReceived > 0) {
        buffer[bytesReceived] = '\0';
        std::cout << "Received from server: " << buffer << std::endl;
    }

    close(clientSocketFd);
}

int main() {
    StartTcpClient();
    return 0;
}

UDP 套接字

UDP 套接字使用无连接的 UDP 协议,适用于需要快速传输但不需要可靠性的应用(如视频流、在线游戏等)。

Socket server端

#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <cstring>

constexpr const char *SERVER_IP = "127.0.0.1"; // 本地回环地址
constexpr const int SERVER_PORT = 8080; // 端口号

void StartUdpServer() {
    int serverSocketFd = socket(AF_INET, SOCK_DGRAM, 0);
    if (serverSocketFd == -1) {
        std::cerr << "Error creating socket" << std::endl;
        return;
    }

    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
    serverAddr.sin_port = htons(SERVER_PORT);

    if (bind(serverSocketFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {
        std::cerr << "Error binding socket" << std::endl;
        close(serverSocketFd);
        return;
    }

    std::cout << "UDP Server is listening for incoming messages..." << std::endl;

    while (true) {
        char buffer[256];
        sockaddr_in clientAddr;
        socklen_t clientAddrLen = sizeof(clientAddr);
        ssize_t bytesReceived = recvfrom(serverSocketFd, buffer, sizeof(buffer) - 1, 0,
                                         (struct sockaddr *)&clientAddr, &clientAddrLen);
        if (bytesReceived > 0) {
            buffer[bytesReceived] = '\0';
            std::cout << "Received data: " << buffer << std::endl;

            // 发送响应给客户端
            const char *response = "OK";
            sendto(serverSocketFd, response, strlen(response), 0,
                   (struct sockaddr *)&clientAddr, clientAddrLen);
        }
    }

    close(serverSocketFd);
}

int main() {
    StartUdpServer();
    return 0;
}

Socket client端

#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <cstring>

constexpr const char *SERVER_IP = "127.0.0.1"; // 本地回环地址
constexpr const int SERVER_PORT = 8080; // 端口号

void StartUdpClient() {
    int clientSocketFd = socket(AF_INET, SOCK_DGRAM, 0);
    if (clientSocketFd == -1) {
        std::cerr << "Error creating socket" << std::endl;
        return;
    }

    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
    serverAddr.sin_port = htons(SERVER_PORT);

    const char *message = "Hello from UDP client!";
    sendto(clientSocketFd, message, strlen(message), 0,
           (struct sockaddr *)&serverAddr, sizeof(serverAddr));

    char buffer[256];
    sockaddr_in fromAddr;
    socklen_t fromAddrLen = sizeof(fromAddr);
    ssize_t bytesReceived = recvfrom(clientSocketFd, buffer, sizeof(buffer) - 1, 0,
                                     (struct sockaddr *)&fromAddr, &fromAddrLen);
    if (bytesReceived > 0) {
        buffer[bytesReceived] = '\0';
        std::cout << "Received from server: " << buffer << std::endl;
    }

    close(clientSocketFd);
}

int main() {
    StartUdpClient();
    return 0;
}


http://www.kler.cn/a/304048.html

相关文章:

  • MicroPythonBLEHID使用说明——蓝牙鼠标
  • yolov7论文翻译
  • Python数据预处理
  • 运行springBlade项目历程
  • Nebula NGQL语言的使用 一
  • spring cloud 入门笔记1(RestTemplate,Consul)
  • 基于Python的B站热门视频可视化分析与挖掘系统
  • 伊顿穆勒Moeller控制器电源维修easy 619-AC-RCX
  • CAESES许可证转移方法
  • Keras深度学习中文文本分类
  • wopop靶场漏洞挖掘练习
  • 【数学建模国赛】写作心得
  • 搜维尔科技:AcuMap - 针灸模拟VR训练解决方案
  • Leetcode 109.有序链表转换二叉搜索树(Medium)
  • Android Studio 安装2022版稳定版 2022.3.1 详细操作(带图展示)
  • OpengGL教程(三)---使用VAO和VBO方式绘制三角形
  • 02 Docker基本管理
  • 个性化、持续性阅读 学生英语词汇量自然超越标准
  • 智慧交通基于yolov8的行人车辆检测计数系统python源码+onnx模型+精美GUI界面
  • Camera2 预览旋转方向、拍照、录像成像旋转
  • Pytorch维度转换操作:view,reshape,permute,flatten函数详解
  • 计算左边(比自己小的元素)的最长距离
  • Linux中常见的Docker问题及解决方法
  • Oracle rman 没有0级时1级备份和0级大小一样,可以用来做恢复 resetlogs后也可以
  • 基于python+django+vue的农业管理系统
  • 2024北京IC WORLD大会圆满收官!高频科技收获满满,同“芯”共促产业发展