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

相关推荐
yuanpan36 分钟前
ubuntu系统上的conda虚拟环境导出方便下次安装
linux·ubuntu·conda
云边云科技1 小时前
零售行业新店网络零接触部署场景下,如何选择SDWAN
运维·服务器·网络·人工智能·安全·边缘计算·零售
AOwhisky1 小时前
Linux 文本处理三剑客:awk、grep、sed 完全指南
linux·运维·服务器·网络·云计算·运维开发
Gavin_9152 小时前
从零开始部署经典开源项目管理系统最新版redmine6-Linux Debian12
linux·ruby on rails·开源·debian·ruby·redmine
花小璇学linux2 小时前
imx6ull-驱动开发篇31——Linux异步通知
linux·驱动开发·嵌入式软件
shelutai2 小时前
ubuntu 编译ffmpeg6.1 增加drawtext,libx264,libx265等
linux·ubuntu·ffmpeg
runfarther3 小时前
搭建LLaMA-Factory环境
linux·运维·服务器·python·自然语言处理·ai编程·llama-factory
hello_ world.3 小时前
RHCA10NUMA
linux
神秘人X7074 小时前
Linux高效备份:rsync + inotify实时同步
linux·服务器·rsync
轻松Ai享生活4 小时前
一步步学习Linux initrd/initramfs
linux