其他分享
首页 > 其他分享> > 嵌入式系统c语言socket之udpserver

嵌入式系统c语言socket之udpserver

作者:互联网

 

static pthread_t udp_server_thread;
static pthread_attr_t udp_server_attr;

static int udp_sock_init(void)
{
int sockfd;
int ret = 0;
struct sockaddr_in ser_addr;

sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0)
{
printf("create socket fail!\n");
return -1;
}
memset(&ser_addr, 0, sizeof(ser_addr));
ser_addr.sin_family = AF_INET;
ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
ser_addr.sin_port = htons(5688);
ret = bind(sockfd, (struct sockaddr*)&ser_addr, sizeof(ser_addr));
if(ret < 0)
{
printf("socket bind fail!\n");
return -1;
}
return sockfd;
}

/*******************************************************************
* function name : udp_server
* desc : server 主任务入口(以后功能的拓展),作为配置通道
* input param :
* output param :
* return value :
* writer : wishdom.zzzx
* data : 2020/12/15
********************************************************************/
void *udp_server(void *parameter)
{

int sockfd;
sockfd = udp_sock_init();

if (sockfd <= 0)
{
printf("socket init error!\n");
return 0;
}

while(1)
{
struct sockaddr_in src;
socklen_t src_len = sizeof(src);

static char udp_str[1024] = {0};
int udp_len = 0;

udp_len = recvfrom(sockfd, udp_str, sizeof(udp_str), 0, (struct sockaddr *)&src, &src_len);

if (udp_len > 0)
{
uint32_t json_ret = 0;
printf("unix recv len %d %s \n", udp_len, udp_str);
pthread_mutex_lock(&cfg_mutex);
json_ret = mm_load_cfg_from_str(udp_str);
pthread_mutex_unlock(&cfg_mutex);

if (0 == json_ret ) //(json_ret & IS_CONFIG_MSG)
{
printf("recv config msg\n");
pthread_mutex_lock(&cfg_mutex);
mm_config_save();
pthread_mutex_unlock(&cfg_mutex);
}
}
}
return 0;
}

/*******************************************************************
* function name : udp_server_init
* desc : server 任务初始化
* input param :
* output param :
* return value :
* writer : wishdom.zzzx
* data : 2020/12/15
********************************************************************/
int udp_server_init(void)
{
int rc;

pthread_attr_init(&udp_server_attr);
pthread_attr_setdetachstate(&udp_server_attr, PTHREAD_CREATE_DETACHED);

rc = pthread_create(&udp_server_thread, &udp_server_attr, udp_server, NULL);

if (rc)
{
printf("Error : unable to create thread socket_server\n");
return 1;
}
pthread_attr_destroy(&udp_server_attr);
return 0;
}

标签:udp,return,addr,server,pthread,sockfd,udpserver,嵌入式,socket
来源: https://www.cnblogs.com/wishdom-zzzx/p/14490144.html