Linux C/C++TCP通信实现

文章目录

  • 一、TCP通信流程
  • 二、使用步骤
    • 1.TCP(客户端)
    • 2.TCP(服务器端)
  • 总结


一、TCP通信流程

Linux C/C++TCP通信实现_第1张图片

二、使用步骤

1.TCP(客户端)

//  TCP通信客户端

#include
#include
#include
#include
#include

int main()
{
    //1.创建套接字
    int fd = socket(AF_INET, SOCK_STREAM, 0);

    if(fd==-1)
    {
        perror("socket");
        exit(-1);
    }

    //2.连接服务器
    struct sockaddr_in saddr;
    inet_pton(AF_INET, "x.x.x.x", &saddr.sin_addr.s_addr);
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(9999);
    int ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));

    if(ret==-1)
    {
        perror("connet");
        exit(-1);
    }

    //3.通信
    char recvbuf[1024] = {0};
    while(1)
    {
        char *data = "hello ,i am client";
        write(fd, data, strlen(data));
        sleep(1);
        int lens = read(fd, recvbuf, sizeof(recvbuf));
        if(lens==-1)
        {
            perror("read");
            exit(-1);
        }else if(lens>0)
        {
            printf("recv server data: %s\n", recvbuf);
        }else if(lens==0)
        {//表示客户端断开连接
            printf("server closed...");
        }
    }
    

    //关闭连接
    close(fd);

    return 0;
}

2.TCP(服务器端)

//TCP通信服务端

#include
#include
#include
#include
#include

int main()
{
    //1.创建socket(用于监听的套接字)
    int lfd = socket(AF_INET, SOCK_STREAM, 0);

    if(lfd==-1)
    {
        perror("socket");
        exit(-1);
    }

    //2.绑定
    struct sockaddr_in saddr;
    saddr.sin_family = PF_INET;
    saddr.sin_addr.s_addr = INADDR_ANY; //0.0.0.0
    saddr.sin_port = htons(9999);
    int ret = bind(lfd, (struct sockaddr *)&saddr, sizeof(saddr));

    if(ret == -1)
    {
        perror("bind");
        exit(-1);
    }

    //3.监听
    listen(lfd, 5);
    if(ret==-1)
    {
        perror("listen");
        exit(-1);
    }

    //4.接受客户端连接
    struct sockaddr_in caddr;
    socklen_t len = sizeof(caddr);
    int cfd = accept(lfd, (struct sockaddr *)&caddr, &len);

    if(cfd==-1)
    {
        perror("accept");
        exit(-1);
    }

    //输出客户端的信息
    char cip[16];
    inet_ntop(AF_INET, &caddr.sin_addr.s_addr, cip, sizeof(cip));
    unsigned short cport = ntohs(caddr.sin_port);
    printf("client ip is %s,port is %d\n", cip, cport);

    //5.
    //获取客户端的数据
    char recvbuf[1024] = {0};
    while(1)
    {
        int lens = read(cfd, recvbuf, sizeof(recvbuf));
        if(lens==-1)
        {
            perror("read");
            exit(-1);
        }else if(lens>0)
        {
            printf("recv client data: %s\n", recvbuf);
        }else if(lens==0)
        {//表示客户端断开连接
            printf("client closed...");
            break;
        }

        //给客户端发送数据
        char *data = "hello ,i am server";
        write(cfd, data, strlen(data));
    }
   

    //关闭文件描述符
    close(lfd);
    close(cfd);

    return 0;
}

总结

TCP的通信流程主要是这种模式。

你可能感兴趣的:(c++,c,Linux,linux,tcp/ip,c++,c语言,ubuntu)