我尝试在nucleo-f746zg上进行UDP Echo Serverur
这是我的线程代码:
static void udpecho_thread(void *arg)
{
err_t err, recv_err;
LWIP_UNUSED_ARG(arg);
conn = netconn_new(NETCONN_UDP);
if (conn != NULL)
{
err = netconn_bind(conn, '0xc0a8b26f', 8);
if (err == ERR_OK)
{
while (1)
{
recv_err = netconn_recv(conn, &buf);
if (recv_err == ERR_OK)
{
addr = netbuf_fromaddr(buf);
port = netbuf_fromport(buf);
netconn_connect(conn, addr, port);
buf->addr.addr = 0;
netconn_send(conn, buf);
netbuf_delete(buf);
}
}
}
else
{
netconn_delete(conn);
}
}
}
在计算机上工作的客户端:
Hostname 192.168.178.111 resolved as 192.168.178.111
Reply from 192.168.178.111:8, time 46 ms OK
Une connexion existante a dû être fermée par l'hôte distant
Une connexion existante a dû être fermée par l'hôte distant
Une connexion existante a dû être fermée par l'hôte distant
Une connexion existante a dû être fermée par l'hôte distant
Statistics: Received=1, Corupted=0, Lost=0
这是可以预期的。
err = netconn_bind(conn, '0xc0a8b26f', 8);
仅在线程开始时调用,然后内部是始终工作的循环。例如,仅允许执行1个。
您可以考虑将此功能重写与此类似的内容:
static void udpecho_thread(void *arg) {
err_t err, recv_err;
LWIP_UNUSED_ARG(arg);
while (1) { /* Add this loop */
conn = netconn_new(NETCONN_UDP);
if (conn != NULL) {
err = netconn_bind(conn, '0xc0a8b26f', 8);
if (err == ERR_OK) {
while (1) {
recv_err = netconn_recv(conn, &buf);
if (recv_err == ERR_OK) {
addr = netbuf_fromaddr(buf);
port = netbuf_fromport(buf);
netconn_connect(conn, addr, port);
buf->addr.addr = 0;
netconn_send(conn,buf);
netbuf_delete(buf);
} else {
break; /* Add break to stop inner loop */
}
}
}
netconn_delete(conn);
}
}
}
您知道,格式化代码非常容易
回声的解决方案是:
static void udpecho_thread(void *arg) {
err_t err, recv_err;
LWIP_UNUSED_ARG(arg);
while (1) { /* Add this loop */
conn = netconn_new(NETCONN_UDP);
if (conn!= NULL) {
err = netconn_bind(conn, '0xc0a8b26f', 8);
if (err == ERR_OK) {
while (1) {
recv_err = netconn_recv(conn, &buf);
if (recv_err == ERR_OK) {
addr = netbuf_fromaddr(buf);
port = netbuf_fromport(buf);
netconn_sendto(conn,buf,addr,port);
netbuf_delete(buf);
}
}
} else {
netconn_delete(conn);
}
}
}
}