c语言——简单客户端demo

以下是一个简单的C语言客户端示例,用于连接到服务器并发送和接收数据:

复制代码
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <sys/socket.h>  
#include <arpa/inet.h>  
#include <unistd.h>  
  
#define SERVER_ADDRESS "127.0.0.1"  
#define SERVER_PORT 12345  
#define BUFFER_SIZE 1024  
  
int main(int argc, char *argv[]) {  
    int sockfd;  
    struct sockaddr_in server_addr;  
    char buffer[BUFFER_SIZE];  
    int bytes_received;  
  
    // 创建socket  
    sockfd = socket(AF_INET, SOCK_STREAM, 0);  
    if (sockfd < 0) {  
        perror("Error creating socket");  
        exit(EXIT_FAILURE);  
    }  
  
    // 设置服务器地址和端口号  
    memset(&server_addr, 0, sizeof(server_addr));  
    server_addr.sin_family = AF_INET;  
    server_addr.sin_addr.s_addr = inet_addr(SERVER_ADDRESS);  
    server_addr.sin_port = htons(SERVER_PORT);  
  
    // 连接服务器  
    if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {  
        perror("Error connecting to server");  
        exit(EXIT_FAILURE);  
    }  
    printf("Connected to server\n");  
  
    // 发送数据到服务器  
    strcpy(buffer, "Hello, server!");  
    if (send(sockfd, buffer, strlen(buffer), 0) < 0) {  
        perror("Error sending data");  
        exit(EXIT_FAILURE);  
    }  
    printf("Data sent to server: %s\n", buffer);  
  
    // 接收服务器发送的数据  
    bytes_received = recv(sockfd, buffer, BUFFER_SIZE, 0);  
    if (bytes_received < 0) {  
        perror("Error receiving data");  
        exit(EXIT_FAILURE);  
    }  
    buffer[bytes_received] = '\0';  
    printf("Data received from server: %s\n", buffer);  
  
    // 关闭socket连接  
    close(sockfd);  
    printf("Connection closed\n");  
    return 0;  
}

在上述代码中,我们使用了socket()函数创建了一个TCP socket,并指定了使用IPv4协议和TCP传输协议。然后,我们使用connect()函数连接到指定的服务器,其中服务器地址和端口号分别由常量SERVER_ADDRESSSERVER_PORT定义。在连接成功后,我们使用send()函数发送了一条消息到服务器,然后使用recv()函数接收服务器发送的响应。最后,我们使用close()函数关闭了socket连接。

相关推荐
linweidong2 小时前
C++ 模块化编程(Modules)在大规模系统中的实践难点?
linux·前端·c++
invicinble7 小时前
对linux形成认识
linux·运维·服务器
小Pawn爷7 小时前
14.VMmare安装ubuntu
linux·运维·ubuntu
技术路上的探险家7 小时前
8 卡 V100 服务器:基于 vLLM 的 Qwen 大模型高效部署实战
运维·服务器·语言模型
半桔7 小时前
【IO多路转接】高并发服务器实战:Reactor 框架与 Epoll 机制的封装与设计逻辑
linux·运维·服务器·c++·io
绵绵细雨中的乡音7 小时前
深入理解 ET 与 LT 模式及其在 Reactor 模型中的应用
服务器·网络·php
HABuo8 小时前
【linux文件系统】磁盘结构&文件系统详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
Howrun7778 小时前
关于Linux服务器的协作问题
linux·运维·服务器
小白同学_C9 小时前
Lab3-page tables && MIT6.1810操作系统工程【持续更新】
linux·c/c++·操作系统os
十年磨一剑~10 小时前
Linux程序接收到sigpipe信号崩溃处理
linux