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

相关推荐
IMPYLH11 分钟前
Linux 的 wc 命令
linux·运维·服务器·前端·bash
zxy64449247322 分钟前
Centos7.9编译安装PHP7.4
linux·运维·服务器
无限进步_25 分钟前
【Linux】从冯诺依曼到操作系统:理解计算机运行的基本脉络
linux·运维·服务器
happybasic27 分钟前
Python库升级标准流程~
linux·前端·python
为何创造硅基生物35 分钟前
C 语言 typedef 结构体私有化
c语言·开发语言·算法
Rabbit_QL1 小时前
【ln -s】Linux 软链接在大模型部署中的应用
linux·运维·服务器
坤昱1 小时前
cfs调度类深入解刨——核心结构细节分析
linux·cfs调度·eevdf调度·linux调度·linux技术
希望永不加班1 小时前
var局部变量类型推断的利弊
java·服务器·前端·javascript·html
枳实-叶1 小时前
【Linux驱动开发】第12天:Linux设备树核心:树形结构+节点+属性 完整全解
linux·运维·驱动开发
Yeats_Liao1 小时前
物联网接入层技术剖析(三):epoll在JVM中的映射
java·linux·jvm·人工智能·物联网