tcpecho.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <lwip/api.h>
  2. #define TCP_ECHO_PORT 7
  3. void tcpecho_entry(void *parameter)
  4. {
  5. struct netconn *conn, *newconn;
  6. err_t err;
  7. /* Create a new connection identifier. */
  8. conn = netconn_new(NETCONN_TCP);
  9. /* Bind connection to well known port number 7. */
  10. netconn_bind(conn, NULL, TCP_ECHO_PORT);
  11. /* Tell connection to go into listening mode. */
  12. netconn_listen(conn);
  13. while(1)
  14. {
  15. /* Grab new connection. */
  16. newconn = netconn_accept(conn);
  17. /* Process the new connection. */
  18. if(newconn != NULL)
  19. {
  20. struct netbuf *buf;
  21. void *data;
  22. u16_t len;
  23. while((buf = netconn_recv(newconn)) != NULL)
  24. {
  25. do
  26. {
  27. netbuf_data(buf, &data, &len);
  28. err = netconn_write(newconn, data, len, NETCONN_COPY);
  29. if(err != ERR_OK){}
  30. }
  31. while(netbuf_next(buf) >= 0);
  32. netbuf_delete(buf);
  33. }
  34. /* Close connection and discard connection identifier. */
  35. netconn_delete(newconn);
  36. }
  37. }
  38. }
  39. #ifdef RT_USING_FINSH
  40. #include <finsh.h>
  41. static rt_thread_t echo_tid = RT_NULL;
  42. void tcpecho(rt_uint32_t startup)
  43. {
  44. if (startup && echo_tid == RT_NULL)
  45. {
  46. echo_tid = rt_thread_create("echo",
  47. tcpecho_entry, RT_NULL,
  48. 512, 30, 5);
  49. if (echo_tid != RT_NULL)
  50. rt_thread_startup(echo_tid);
  51. }
  52. else
  53. {
  54. if (echo_tid != RT_NULL)
  55. rt_thread_delete(echo_tid); /* delete thread */
  56. echo_tid = RT_NULL;
  57. }
  58. }
  59. FINSH_FUNCTION_EXPORT(tcpecho, startup or stop TCP echo server);
  60. #endif