linux系统编程(十③)RK3568 socket之 TCP 服务器的实现【更新客户端断开重连依旧可以收发】

这里对上一篇:https://blog.csdn.net/u012507643/article/details/153483336?spm=1011.2124.3001.6209

服务器编程再客户端断开重连后不能响应的解决办法

直接上程序【这里解决的思路还是和tcp客户端连接服务器的方式一样,用MSG_PEEK去看下recv】

复制代码
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/tcp.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>




int main(int argc, char *argv[])
{
    int fd, client_fd;
    struct sockaddr_in s;
    struct sockaddr_in c;
    int len = sizeof(c), rlen = 0;
    char rx_buf[1024] = {0};

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
    {
        printf("create socekt failed\n");
        return 1;
    }

    s.sin_family = AF_INET;
    s.sin_port = htons(8089);
    //s.sin_addr.s_addr = INADDR_ANY;
    inet_pton(AF_INET, "192.168.31.96", &s.sin_addr);
    bind(fd, (const struct sockaddr *)&s, sizeof(s));

    printf("start listen\n");
    if (listen(fd, 10) < 0) {
        printf("listen failed\n");
        return 1;
    }

    printf("server ip:192.168.31.96,port:8089\n");

    /* 返回连接上来的套接字 */
    client_fd = accept(fd, (struct sockaddr *)&c, &len);
    if (client_fd < 0)
    {
        printf("sccept failed\n");
        return 1;
    }
    printf("new client %d connected\n", client_fd);
    while(1)
    {
        int ret = recv(client_fd, rx_buf, sizeof(rx_buf), MSG_PEEK);
        if ((ret > 0) || (ret == -1 && errno == EAGAIN))
        {
            rlen = recvfrom(client_fd, rx_buf, sizeof(rx_buf), MSG_DONTWAIT, (struct sockaddr *)&c, &len);
            if (rlen > 0)
            {
                printf("recv[%s:%d] data:%s,len=%d\n", inet_ntoa(c.sin_addr), ntohs(c.sin_port), rx_buf, rlen);
                send(client_fd, rx_buf, rlen, MSG_DONTWAIT);
                memset(rx_buf, 0, sizeof(rx_buf));
            }
        } else {
            printf("clinet %d disconnectted\n", client_fd);
            close(client_fd);
            len = sizeof(c);
            /* 返回连接上来的套接字 */
            client_fd = accept(fd, (struct sockaddr *)&c, &len);
            if (client_fd < 0)
            {
                printf("sccept failed\n");
                return 1;
            } else {
                printf("new clinet fd=%d connectted\n", client_fd);
            }
        }
    }

    close(fd);
    close(client_fd);
    return 0;
}
相关推荐
Genie cloud7 分钟前
1Panel SSL证书申请完整教程
服务器·网络协议·云计算·ssl
一只自律的鸡21 分钟前
【Linux驱动】bug处理 ens33找不到IP
linux·运维·bug
17(无规则自律)37 分钟前
【CSAPP 读书笔记】第二章:信息的表示和处理
linux·嵌入式硬件·考研·高考
!chen37 分钟前
linux服务器静默安装Oracle26ai
linux·运维·服务器
莫大33040 分钟前
2核2G云服务器PHP8.5+MySQL9.0+Nginx(LNMP)安装WordPress网站详细教程
运维·服务器·nginx
REDcker1 小时前
Linux 文件描述符与 Socket 选项操作详解
linux·运维·网络
蒹葭玉树1 小时前
【C++上岸】C++常见面试题目--操作系统篇(第二十八期)
linux·c++·面试
2501_927773071 小时前
imx6驱动
linux·运维·服务器
hy____1232 小时前
Linux_进程间通信
linux·运维·服务器
郭涤生2 小时前
C++的函数是否可以做到完全覆盖Linux和windows的跨平台
linux·c++·windows