一个简单的UDP接收例子

一个简单的UDP Server例程:将UDP接收的数据显示出来,配合线程使用,更接近实际应用场景。(可自行在适当的地方添加数据发送函数)

由于个人水平有限,文中疏忽和不足的地方恳请指正
转载请保留原文地址 —— [ CLICK ME ]
http://blog.csdn.net/a99778800/article/details/53659458

测试环境: ubuntu + gcc;

udp_server.c
gcc -o udp_server udp_server.c -lpthread

/* author: ljf    
 * udp_server.c
 */
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>


int isRecvData = 0;

int g_size = 0; 
unsigned char g_buffer[1024] = {0}; 

void *thread_udp_recv(void *arg)
{    
    int fd = *(int *)arg;

    int recvLen = 0; 
    unsigned char recvDataBuff[1024] = {0}; // 逻辑上区别不同缓冲区,可直接使用g_buffer;   

    struct sockaddr_in from;
    int fromlen = sizeof(from);

    printf("thread: begin;\r\n");

    while(1)    
    {
        recvLen = recvfrom(fd, recvDataBuff, 1024, 0, (struct sockaddr *)&from, &fromlen);
        if(-1 == recvLen)        
        {
            g_size = -1;
            perror("recvfrom");
            break;
        }

        while(1 == isRecvData); // wait for show data;        

        if(recvLen > 0){
            memcpy(g_buffer, recvDataBuff, recvLen);
            g_size = recvLen;
            isRecvData = 1;                    
            printf("thread: %d byte data from %s:%d;\r\n", recvLen, inet_ntoa(from.sin_addr), ntohs(from.sin_port));
        }
    }

    return NULL;
}

int main(int argc, char **argv)
{

    int sockfd = 0;    
    struct sockaddr_in local_addr;
    pthread_t tid_udp_recv; // 线程ID;  

    // 1. 创建套接字;
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);    // IPv4以太网协议/数据包套接字;
    if(-1 == sockfd)
    {
        perror("socket");
        return -1;
    }
    printf("sockfd = %d\n", sockfd);

    // 2. 绑定服务器端口号;(也可以不绑定,由系统分配可用端口号)
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(9000);
    local_addr.sin_addr.s_addr = INADDR_ANY; // 任意地址;
    bzero(&local_addr.sin_zero, 8);
    if(-1 == bind(sockfd, (struct sockaddr*)&local_addr, sizeof(local_addr)))
    {
        perror("bind");
        close(sockfd);
        return -1;
    }

    // 3. 启动接收线程;
    pthread_create(&tid_udp_recv, NULL, thread_udp_recv, &sockfd);

    while(g_size >= 0)
    {
        if(isRecvData){
            // show data;
            printf("main: new data\r\n");
            for(int temp = 0; temp < g_size; temp++){
                printf("%02x ", g_buffer[temp]);
            }
            printf("\n");
            isRecvData = 0;
        }
    }

    pthread_join(tid_udp_recv, NULL);
    close(sockfd);

    return 0;
}
发布了9 篇原创文章 · 获赞 7 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览