⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udpserver.c

📁 一个收集所有最基本功能的函数库;所有的函数都是尽量短小和简单 使用 doxygen 生成文档 所有代码以在 Linux 系统上可以编译并运行为准;每当在 lib 目录里增加了一个功能函数
💻 C
字号:
/*************************************************************************** *            udpserver.c * *  Mon May 21 21:40:55 2007 *  Copyright  2007  kf701 *  Email <kf701.ye AT gmail.com> ****************************************************************************//* *  This program is free software; you can redistribute it and/or modify *  it under the terms of the GNU General Public License as published by *  the Free Software Foundation; either version 2 of the License, or *  (at your option) any later version. * *  This program is distributed in the hope that it will be useful, *  but WITHOUT ANY WARRANTY; without even the implied warranty of *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the *  GNU General Public License for more details. * *  You should have received a copy of the GNU General Public License *  along with this program; if not, write to the Free Software *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <sys/types.h>#include <sys/select.h>#include <netinet/in.h>#include <arpa/inet.h>#include <netdb.h>#include "kf701.h"/**  * @brief UDP server use select * * Open a listen socket and read data, * then deleve data to FUNC, the user defined  * FUNC deal with data. *  * Note: dup addr and buf before create thread in FUNC * * @param port listen port * @param psize the UDP server MAX size protocol data * @param func user defined FUNC for deal with data */void udp_server( uint16_t port, uint32_t psize, udp_data_func func){	if( psize <= 0 || func == NULL )	{		sys_message("%s,%d: argu err\n", __FILE__, __LINE__);		return ;	}		int sockfd = open_udp( port );	if( -1 == sockfd )	{		sys_message("%s,%d: open sock err,%m\n", __FILE__, __LINE__);		return ;	}	struct sockaddr_in  addr;	socklen_t len = sizeof( struct sockaddr_in );		fd_set readset;	FD_ZERO(&readset);	FD_SET( sockfd , &readset );		int max_fd = sockfd , select_ret, nread;	uint8_t buf[ psize ];		while( 1 )	{		select_ret = select(max_fd+1, &readset, NULL, NULL, NULL);		if ( select_ret < 0 )		{			sys_message("%s,%d: select err,%m\n", __FILE__, __LINE__);			continue;		}			if ( FD_ISSET (sockfd, &readset) )		{			nread = recvfrom(sockfd, (void*)buf, sizeof(buf) ,0, (struct sockaddr*)&addr, &len);			if( nread <= 0 )			{				sys_message("%s: recvfrom err\n", __func__);				continue;			}			sys_log("%s,%d: read from %s\n",__FILE__,__LINE__,inet_ntoa(addr.sin_addr));			sys_log("%s,%d: read data len = %d\n", __FILE__, __LINE__, nread);			/* Note: dup addr and buf before create thread in func */			func( (struct sockaddr*)&addr, buf, nread );		}	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -