记录STM32使用udp通信的一个大坑

@TOCfreeRTOS+lwip实现udp通信

问题说明

在使用MCU和其他终端udp通信时遇见这样的一个大坑,整个通信过程如下图所示
在这里插入图片描述
问题出在mcu与其他设备通过udp交互,但在调试的过程中发现MCU给其他设备发消息的时候,虽然看起来成功了,但实际上其他设备并没有收到udp消息,经过苦思冥想以及实验,发现代码应该像下面这样写才可以成功的发送udp消息。

代码

//udp channel init
void udp_channel_init() {

	IP_ADDR4(&remoteip,192,168,28,180);
	
	global_udp_conn_pcb = udp_new();
	
	local_port = 7070;
	remote_port = 8999;
	
	
	
	if (udp_bind(global_udp_conn_pcb, IP_ADDR_ANY, local_port) == ERR_OK) {
					
					udp_recv(global_udp_conn_pcb, udp_recv_callback, NULL);
		 } else {
				printf("bind local port fail\n");
		}
		
		#if 1
		if (udp_connect(global_udp_conn_pcb, &remoteip, remote_port) == ERR_OK) {
					
			
		 } else {
				printf("connect remote fail\n");
		}
		#endif
	
}

出了上面的代码之外,在发送消息的前面需要再“”连接“”一次远程(即下面的err = udp_connect(global_udp_conn_pcb, &remoteip, remote_port);),代码如下

/*
 * when recv set dsp msg from platform then call it
 * @json_str: Package cjson msg
 * udp send msg to dsp 
 */
err_t create_udp_client_send_task(char *json_str)
{
	struct pbuf* msg;
	int buflen;
	int timeout;
	err_t err;
	
	buflen = strlen(json_str)+1;
	//memcpy(msg->payload, json_str, buflen);
	#if 1	
		msg=pbuf_alloc(PBUF_TRANSPORT,buflen,PBUF_RAM); 
		if(msg) {
			pbuf_take(msg,json_str,buflen); 
			//udp_send(global_udp_conn_pcb,msg);
			err = udp_connect(global_udp_conn_pcb, &remoteip, remote_port);
			err = udp_sendto(global_udp_conn_pcb, msg, &remoteip, remote_port);
			if (err != ERR_OK) {
					printf("udp_sendto failed\n");
			}
		
		} 
#endif 

	pbuf_free(msg);
	
	return ERR_OK;								
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值