UDP服务recvfrom函数设置非阻塞_recvfrom非阻塞模式-程序员宅基地

技术标签: UDP  udp  socket  



基本概念:

其实UDP的非阻塞也可以理解成和TCP是一样的,都是通过socket的属性去做。

方法一:通过fcntl函数将套接字设置为非阻塞模式

方法二:通过套接字选项SO_RECVTIMEO设置超时。


方法一源码,编译:g++ udp_server.cpp -o server

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <strings.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>

void Perror(const char *s)
{
    perror(s);
    exit(EXIT_FAILURE);
}

//设置非阻塞
static void setnonblocking(int sockfd) {
    int flag = fcntl(sockfd, F_GETFL, 0);
    if (flag < 0) {
        Perror("fcntl F_GETFL fail");
        return;
    }
    if (fcntl(sockfd, F_SETFL, flag | O_NONBLOCK) < 0) {
        Perror("fcntl F_SETFL fail");
    }
}

int main()
{
    int sockfd;
    int port = 9527;
    struct sockaddr_in servaddr, cliaddr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        Perror("socket failed:");
    }
    setnonblocking(sockfd);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    servaddr.sin_port = htons(port);

    if (bind(sockfd, (sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
        Perror("bind failed:");
    }

    socklen_t len;
    for ( ; ; ) {
        char mesg[1024] = {};
        int n = recvfrom(sockfd, mesg, 1024, 0, (sockaddr *)&cliaddr, &len);
        sleep(1);
        perror("recvfrom fail: ");
    }

    return 0;
}


方法二源码,编译:g++ udp_server.cpp -o server

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <strings.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>

void Perror(const char *s)
{
    perror(s);
    exit(EXIT_FAILURE);
}

int main()
{
    int sockfd;
    int port = 9527;
    struct sockaddr_in servaddr, cliaddr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        Perror("socket failed:");
    }

    // 设置超时
    struct timeval timeout;
    timeout.tv_sec = 1;//秒
    timeout.tv_usec = 0;//微秒
    if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) {
        Perror("setsockopt failed:");
    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    servaddr.sin_port = htons(port);

    if (bind(sockfd, (sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
        Perror("bind failed:");
    }
    
    socklen_t len;
    for ( ; ; ) {
        char mesg[1024] = {};
        int n = recvfrom(sockfd, mesg, 1024, 0, (sockaddr *)&cliaddr, &len);
        perror("recvfrom fail: ");

    }

    return 0;
}


原文出自:http://blog.csdn.net/daiyudong2020/article/details/70039409


End;

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/daiyudong2020/article/details/70039409

智能推荐

如何在Google和其他高科技公司获得软件工程师职位-程序员宅基地

文章浏览阅读510次。by YK Sugi 由YK Sugi 如何在Google和其他高科技公司获得软件工程师职位 (How to Get a Software Engineer Job at Google and Other Top Tech Companies)Hi everyone! 嗨,大家好! I’ve already talked about how I personally got a softw..._获得谷歌的软件工程师职位英语

steam密码查看_如何查看和清除Steam中的先前别名-程序员宅基地

文章浏览阅读3.5k次。steam密码查看Steam lets you set your name to anything within its terms of service. This can make it difficult to find people—even if they’re already on your friends list. Find out who’s who by checking al..._steam密码查看

spark和java类型转化时报错:Caused by: java.lang.ClassCastException: scala.collection.mutable_scala.collection.mutable.wrappedarray$ofref is not-程序员宅基地

文章浏览阅读1.3k次。错误:Caused by: java.lang.ClassCastException: scala.collection.mutable.WrappedArray$ofRef cannot be cast to java.util.List分析:这个问题,一般是在sparksql中做row转换时候出错,最好一步步排错。这里要说的是, row:Row是先做了一次强制类型转换(asInstanceOf),row的实际类型是Seq[T],但是不能用Array[T],否则就会出现各种scala和java的类_scala.collection.mutable.wrappedarray$ofref is not a valid external type for

kconfig_对自己的项目使用kconfig-程序员宅基地

文章浏览阅读1.3k次。kconfig 介绍 (Intro)Every Linux professional write scripts. Someеimes light, linear. Sometimes complex script with functions and libs(yes, you can write your bash-library for use in other scripts). 每个..._kconfig 应用程序

opensource项目_2020 Opensource.com夏季阅读列表-程序员宅基地

文章浏览阅读509次。opensource项目 Opensource.com社区充满了各种各样的兴趣; 所有人都因对开源的热爱而聚集在一起。 2020年Opensource.com夏季阅读列表通过涵盖有关广泛主题和不同年龄组的书籍,反映了这些不同的兴趣。 有关数学,密码学,Unix和“编码”沙堡的书籍只是构成今年榜单的部分。 今年的夏季阅读清单也很好地说明了Opensource.com的不断发展和变化的本质。 贡...

遨游5无法加载flash_使用Flash 5优化预加载-程序员宅基地

文章浏览阅读631次。遨游5无法加载flashFlash movies are renowned for being compact and light in file size. That said, it’s amazing how large those compact files can get when audio and a lot of imported graphics are used in a mo..._遨游flash插件

随便推点

symfony 查询数据_Symfony2中的数据装置-程序员宅基地

文章浏览阅读222次。symfony 查询数据Back when I first started to learn Symfony (1.x) with its Jobeet project, I thought the ability to load a bunch of test data into the database very useful. 回到我最初通过Jobeet项目学习Symfony(1.x)时,..._symfony 数组字段查询

ORACLE 查看RMAN的备份信息总结_oracle rman 备份情况-程序员宅基地

文章浏览阅读6.7k次。原文地址:https://www.cnblogs.com/kerrycode/p/5684768.html 关于Oracle数据库的RMAN备份,除了邮件外,是否能通过其它方式检查RMAN备份的成功与失败呢?其实我们可以通过下面SQL脚本来检查某个时间段备份失败的记录:SELECT * FROM V$RMAN_STATUS WHERE START_TIME >= _oracle rman 备份情况

zmq pub/sub使用详解_zmq pub sub-程序员宅基地

文章浏览阅读5.7k次,点赞2次,收藏11次。关于zmq的基本简介,请参考ZeroMQ基础入门。pub/sub模式介绍:————————————————发布/订阅模式,全称为Publish/Subscribe,支持多个发布者/多订阅者,使用在消息单向传输的应用场景,消息总是从发布者发送到订阅者。一般的使用流程为:pub端:创建context 创建socket,设置ZMQ_PUB模式 bind端口 循环发布消息..._zmq pub sub

深入理解vsto,开发word插件的利器_vsto word 插件源码-程序员宅基地

文章浏览阅读3.8k次。开发了vsto,客户那边也有一些反映插件安装失败或者加载不上的情况。于是我下定决定再理解下vsto的工作机制,如下图:    如上图所示,我把vsto的解决方案分为两部分,一部分是vsto Add-ins,另外一部分是Microsoft Office Applications。它们之间是如何交互的呢?要回答这个问题,必须对这两部分有一定的认识。首先vsto Add-ins是我们用c#开..._vsto word 插件源码

ipad上能否适用zoom_Zoom使网站即使在Windows上也无需征得您的同意就开始拍摄您...-程序员宅基地

文章浏览阅读3.7k次。ipad上能否适用zoomZoom’s video conferencing software has more problems than a secret web server on Mac. Even on Windows, websites you visit could start filming you without your consent. All you have to do ..._zoom video conferencing software

Windows 8中无法使用Aero:6个仍可以使用的Aero功能-程序员宅基地

文章浏览阅读1.2k次。Many people think Aero is completely gone in Windows 8, but this isn’t true. Microsoft hasn’t helped matters by saying they’ve “moved beyond Aero” in several blog posts. However, hardware acceleration..._windows aero