echo_server.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * echo_server.c
  3. *
  4. * Created on: Jun 9, 2024
  5. * Author: jakubski
  6. */
  7. #include <stdio.h>
  8. #include "lwip/opt.h"
  9. #include "lwip/arch.h"
  10. #include "lwip/api.h"
  11. #include "cmsis_os.h"
  12. #define ECHOSERVER_THREAD_PRIO ( tskIDLE_PRIORITY + 4 )
  13. void echo_server_thread(void *arg)
  14. {
  15. struct netconn *conn, *newconn;
  16. err_t err, recv_err;
  17. struct netbuf *inbuf;
  18. void *data;
  19. u16_t len;
  20. LWIP_UNUSED_ARG(arg);
  21. /* Create a new TCP connection handle */
  22. /* Bind to port 80 (HTTP) with default IP address */
  23. conn = netconn_new(NETCONN_TCP);
  24. LWIP_ERROR("echo_server: invalid conn", (conn != NULL), return;);
  25. err = netconn_bind(conn, IP_ADDR_ANY, 7);
  26. if (err == ERR_OK)
  27. {
  28. /* Put the connection into LISTEN state */
  29. netconn_listen(conn);
  30. do
  31. {
  32. err = netconn_accept(conn, &newconn);
  33. if (err == ERR_OK)
  34. {
  35. while (( recv_err = netconn_recv(newconn, &inbuf)) == ERR_OK)
  36. {
  37. do
  38. {
  39. netbuf_data(inbuf, &data, &len);
  40. netconn_write(newconn, data, len, NETCONN_COPY);
  41. printf("Echoed %d bytes\r\n", len);
  42. fflush(stdout);
  43. }
  44. while (netbuf_next(inbuf) >= 0);
  45. netbuf_delete(inbuf);
  46. }
  47. netconn_close(newconn);
  48. netconn_delete(newconn);
  49. }
  50. else
  51. {
  52. netconn_delete(newconn);
  53. }
  54. }
  55. while (err == ERR_OK);
  56. // LWIP_DEBUGF(HTTPD_DEBUG, ("echo_server_netconn_thread: netconn_accept received error %d, shutting down", err));
  57. netconn_close(conn);
  58. netconn_delete(conn);
  59. }
  60. }
  61. /** Initialize the ECHO server (start its thread) */
  62. void echo_server_netconn_init(void)
  63. {
  64. sys_thread_new("echo_server_netconn", echo_server_thread, NULL, DEFAULT_THREAD_STACKSIZE, ECHOSERVER_THREAD_PRIO);
  65. }