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

相关推荐
旖旎夜光24 分钟前
Linux(13)(中)
linux·网络
风指引着方向1 小时前
图编译优化全链路:CANN graph-engine 仓库技术拆解
c语言
威迪斯特1 小时前
CentOS图形化操作界面:理论解析与实践指南
linux·运维·centos·组件·图形化·桌面·xserver
一方热衷.1 小时前
在线安装对应版本NVIDIA驱动
linux·运维·服务器
独自归家的兔1 小时前
ubuntu系统安装dbswitch教程 - 备份本地数据到远程服务器
linux·运维·ubuntu
m0_694845571 小时前
tinylisp 是什么?超轻量 Lisp 解释器编译与运行教程
服务器·开发语言·云计算·github·lisp
ONE_SIX_MIX1 小时前
ubuntu 24.04 用rdp连接,桌面黑屏问题,解决
linux·运维·ubuntu
龙飞051 小时前
Systemd -systemctl - journalctl 速查表:服务管理 + 日志排障
linux·运维·前端·chrome·systemctl·journalctl
*小海豚*1 小时前
在linux服务器上DNS正常,但是java应用调用第三方解析域名报错
java·linux·服务器
June`1 小时前
muduo项目排查错误+测试
linux·c++·github·muduo网络库