big_chengzi
big_chengzi
2021-02-26 11:52

LWIP使用tcp_write()和tcp_output()遇到问题

使用lwIP的rawAPI,建立TCP服务端客户端进行文件传输,文件传输期间客户端只接收不发送。

还请各位解答或指点正确使用方法,问题描述:

文件传输代码如下,调用tcp_write()只是将数据copy到发送缓冲区,并不会立即发送,约300~500ms才开始发送数据,导致传输速度慢

while(file_pg < pgCount && transmitting){
	sta = f_read(&fil_read, read_buf, PACK_BUFF_SIZE, &read_num);
	if(sta != FR_OK){
		return -101;
	} 
        sprintf(send_buf,"%s%08d{\"resultCode\":%d,\"pgNum\":%d,\"pgCount\":%d,\"dataLength\":%d}",TRANSFER, 0, code, file_pg, pgCount, read_num);
	len = strlen(send_buf);
	sprintf(data_len, "%08d", len - PACK_HEAD_SIZE);
	memcpy(send_buf + TYPE_SIZE, data_len, LENGTH_SIZE);
	memcpy(send_buf + len, read_buf, read_num);
	len = len + read_num;
		
	while(tcp_sndbuf(target_pcb) < len || tcp_sndqueuelen(target_pcb) != 0)
		OS_MSleep(1);
	err = tcp_write(target_pcb, send_buf, len, TCP_WRITE_FLAG_COPY);
	if(err != ERR_OK){
		return -102;
	}
	file_pg++;
}

在tcp_write()后添加tcp_output(),可以立即将数据发送出去,大幅提高文件传输效率。

 

while(file_pg < pgCount && transmitting){
	sta = f_read(&fil_read, read_buf, PACK_BUFF_SIZE, &read_num);
	if(sta != FR_OK){
		return -101;
	} 
        sprintf(send_buf,"%s%08d{\"resultCode\":%d,\"pgNum\":%d,\"pgCount\":%d,\"dataLength\":%d}",TRANSFER, 0, code, file_pg, pgCount, read_num);
	len = strlen(send_buf);
	sprintf(data_len, "%08d", len - PACK_HEAD_SIZE);
	memcpy(send_buf + TYPE_SIZE, data_len, LENGTH_SIZE);
	memcpy(send_buf + len, read_buf, read_num);
	len = len + read_num;
	//等待发送缓冲区有足够空间和队列	
	while(tcp_sndbuf(target_pcb) < len || tcp_sndqueuelen(target_pcb) != 0)
		OS_MSleep(1);
	err = tcp_write(target_pcb, send_buf, len, TCP_WRITE_FLAG_COPY);
	if(err != ERR_OK){
		return -102;
	}
        err = tcp_output(target_pcb);
        if(err != ERR_OK){
		return -103;
	}
	file_pg++;
}

但如此传输,过程中会打印以下log,然后程序卡在等待缓冲区,在中间debug输出缓冲区空间使用为0,队列使用为1。

 

tcp_receive: valid queue length at line 1032 in src/core/tcp_in.c

如果不判断队列使用为0,只判断有足够的空间进行发送,tcp_write()会返回错误ERE_MEM(-1)。

 

tcp_receive: valid queue length at line 1032 in src/core/tcp_in.c

tcp_write: pbufs on queue => at least one queue non-empty at line 329 in src/core/tcp_out.c

tcp_write error :-1
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

为你推荐