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连接。

相关推荐
Shingmc32 小时前
【Linux】线程互斥与同步
linux
数智化管理手记8 小时前
精益生产中的TPM管理是什么?一文破解设备零故障的密码
服务器·网络·数据库·低代码·制造·源代码管理·精益工程
iFlyCai8 小时前
C语言中的指针
c语言·数据结构·算法
Vect__9 小时前
深刻理解进程、线程、程序
linux
@insist12310 小时前
网络工程师-生成树协议(STP/RSTP/MSTP)核心原理与应用
服务器·开发语言·网络工程师·软考·软件水平考试
末日汐10 小时前
传输层协议UDP
linux·网络·udp
良木生香11 小时前
【C++初阶】:C++类和对象(下):构造函数promax & 类型转换 & static & 友元 & 内部类 & 匿名对象 & 超级优化
c语言·开发语言·c++
无巧不成书021812 小时前
C语言零基础速通指南 | 1小时从入门到跑通完整项目
c语言·开发语言·编程实战·c语言入门·零基础编程·c语言速通
zzzsde12 小时前
【Linux】库的制作和使用(3)ELF&&动态链接
linux·运维·服务器
CQU_JIAKE12 小时前
4.3【A]
linux·运维·服务器