linux 的一个socket 客户端程序

linux 的一个socket 客户端程序

 

#ifndef  __TCP_CLIENT_TEST_1__
#define  __TCP_CLIENT_TEST_1__

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

int main() {
    const char* server_ip = "172.16.126.130";
    const int server_port = 5080;

    // 创建 socket
    int client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket == -1) {
        std::cerr << "Error: Failed to create socket\n";
        return 1;
    }

    // 准备服务器地址结构
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    inet_pton(AF_INET, server_ip, &server_addr.sin_addr);

    // 连接服务器
    if (connect(client_socket, reinterpret_cast<struct sockaddr*>(&server_addr), sizeof(server_addr)) == -1) {
        std::cerr << "Error: Failed to connect to server\n";
        close(client_socket);
        return 1;
    }

    // 发送消息
    int i = 0;
    while (true) {
        std::string message ="(msg_" + std::to_string(i++) + "),hello world server.";
        if (send(client_socket, message.c_str(), message.size(), 0) == -1) {
            std::cerr << "Error: Failed to send message\n";
            break;
        }
        std::cout << "Sent: " << message << std::endl;
        sleep(1); // 每隔 N 秒发送一次消息
    }

    // 关闭 socket
    close(client_socket);
    return 0;
}




#endif 

 

posted @ 2024-04-07 14:04  He_LiangLiang  阅读(15)  评论(0编辑  收藏  举报