lwip 实现tcp服务端 需要代码
时间: 2023-10-04 14:07:34 浏览: 59
以下是一个基本的 LWIP TCP 服务器代码示例:
```c
#include "lwip/sys.h"
#include "lwip/netif.h"
#include "lwip/tcp.h"
#include "netif/etharp.h"
#define TCP_PORT 5005
static struct tcp_pcb *tcp_server_pcb;
err_t tcp_server_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
{
LWIP_UNUSED_ARG(arg);
LWIP_UNUSED_ARG(err);
tcp_setprio(newpcb, TCP_PRIO_MIN);
/* Set up the various callback functions */
tcp_recv(newpcb, tcp_server_recv);
tcp_err(newpcb, tcp_server_error);
tcp_poll(newpcb, tcp_server_poll, 4);
return ERR_OK;
}
err_t tcp_server_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
{
LWIP_UNUSED_ARG(arg);
if (p == NULL)
{
tcp_server_connection_close(tpcb);
}
else
{
tcp_recved(tpcb, p->tot_len);
pbuf_free(p);
}
return ERR_OK;
}
err_t tcp_server_poll(void *arg, struct tcp_pcb *tpcb)
{
LWIP_UNUSED_ARG(arg);
if (tpcb->state == ESTABLISHED)
{
/*send some data*/
tcp_write(tpcb, "Hello, World!", 13, 1);
}
else
{
tcp_server_connection_close(tpcb);
}
return ERR_OK;
}
void tcp_server_error(void *arg, err_t err)
{
LWIP_UNUSED_ARG(arg);
LWIP_UNUSED_ARG(err);
}
void tcp_server_connection_close(struct tcp_pcb *tpcb)
{
/* close tcp connection */
tcp_arg(tpcb, NULL);
tcp_sent(tpcb, NULL);
tcp_recv(tpcb, NULL);
tcp_err(tpcb, NULL);
tcp_poll(tpcb, NULL, 0);
tcp_close(tpcb);
}
void tcp_server_init(void)
{
struct tcp_pcb *pcb;
pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, TCP_PORT);
pcb = tcp_listen(pcb);
tcp_accept(pcb, tcp_server_accept);
tcp_server_pcb = pcb;
}
int main(void)
{
sys_init();
netif_init();
tcp_server_init();
while (1)
{
sys_check_timeouts();
}
return 0;
}
```
这个代码示例启动了一个 TCP 服务器,它监听在 5005 端口上。当一个连接被接受后,它会发送 "Hello, World!" 消息,并在每个 4 秒内轮询该连接。如果连接已经断开,就会关闭该连接。
你需要在你的应用程序中实现 `sys_init()` 和 `sys_check_timeouts()` 函数,这些函数将 LWIP 的系统定时器与你的应用程序的定时器集成。你还需要在你的应用程序中实现 `netif_init()` 函数,它将初始化网络接口。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)