c++ 通讯示例

服务器端

#include <iostream>
#include <string.h> // memset
#include <sys/socket.h>
#include <arpa/inet.h> // inet_addr
#include <unistd.h> // close

int main(int argc, char *argv[])
{
    int server_socket, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    const char* response = "欢迎访问!";

    // 创建 socket
    if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0)
    {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 设置地址结构
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons( 9999 );

    // 绑定 socket 到端口
    if (bind(server_socket, (struct sockaddr *)&address,
             sizeof(address))<0)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 监听连接
    if (listen(server_socket, 3) < 0)
    {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    // 接受连接
    if ((new_socket = accept(server_socket, (struct sockaddr *)&address,
            (socklen_t*)&addrlen))<0)
    {
        perror("accept");
        exit(EXIT_FAILURE);
    }

    // 发送数据
    send(new_socket , response , strlen(response) , 0 );
    printf("消息发送完毕\n");

    // 关闭 socket
    close(new_socket);
    close(server_socket);

    return 0;
}

客户端

#include <iostream>
#include <string.h> // memset
#include <sys/socket.h>
#include <arpa/inet.h> // inet_addr
#include <unistd.h> // close

int main(int argc, char *argv[])
{
    int sock = 0, valread;
    struct sockaddr_in serv_addr;
    const char* message = "Hello Server";
    char buffer[1024] = {0};

    // 创建 socket
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Socket creation error \n");
        return -1;
    }

    // 设置服务器地址
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(9999);

    // 转换 IPv4 和 IPv6 地址
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) 
    {
        printf("\nInvalid address/ Address not supported \n");
        return -1;
    }

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("\nConnection Failed \n");
        return -1;
    }

    // 发送数据
    send(sock , message , strlen(message) , 0 );
    printf("消息发送完毕\n");

    // 接收数据
    valread = read( sock , buffer, 1024);
    printf("%s\n",buffer );

    // 关闭 socket
    close(sock);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值