tcp_server.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "lwip/opt.h"
  2. #include "lwip/sys.h"
  3. #include "tcp_server.h"
  4. #include <string.h>
  5. #include <stdio.h>
  6. #include "gd32f30x.h"
  7. #include "main.h"
  8. #include "lwip/tcp.h"
  9. #include "lwip/memp.h"
  10. #include "lwip/api.h"
  11. #include "sockets.h"
  12. #include "log.h"
  13. void tcp_server_task(void *pvParameters)
  14. {
  15. int ret,sockfd;
  16. int recv_size;
  17. struct sockaddr_in tcpServerSock;
  18. struct sockaddr_in client_sock;
  19. tcpServerSock.sin_family = AF_INET;
  20. inet_aton("192.168.2.222",&(tcpServerSock.sin_addr));
  21. // tcpServerSock.sin_addr.s_addr = htonl(IPADDR_ANY);
  22. tcpServerSock.sin_port = htons(8080);
  23. tcp_server_begin:
  24. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  25. if (sockfd < 0)
  26. {
  27. goto tcp_server_begin;
  28. }
  29. ret = bind(sockfd, (struct sockaddr *)&tcpServerSock, sizeof(tcpServerSock));
  30. if (ret < 0)
  31. {
  32. lwip_close(sockfd);
  33. sockfd = -1;
  34. goto tcp_server_begin;
  35. }
  36. ret = listen(sockfd, 10);
  37. if (ret < 0)
  38. {
  39. lwip_close(sockfd);
  40. sockfd = -1;
  41. goto tcp_server_begin;
  42. }
  43. socklen_t len = sizeof(client_sock);
  44. int client_socket = accept(sockfd, (struct sockaddr*)&client_sock,&len);
  45. if (client_socket<0)
  46. {
  47. printf("error");
  48. }
  49. LOG_PRINT(LOG_INFO,"上位机连接成功");
  50. while (1)
  51. {
  52. vTaskDelay(1000);
  53. char *cmd=pvPortMalloc(1024);
  54. recv_size=recv(client_socket,cmd,1024,0);
  55. if(recv_size>0)
  56. {
  57. LOG_PRINT(LOG_INFO,"服务端recv:%s",cmd);
  58. }
  59. else if(recv_size==0)
  60. {
  61. lwip_close(client_socket);
  62. vPortFree(cmd);
  63. LOG_PRINT(LOG_WARN,"上位机断连,重新等待连接");
  64. client_socket= accept(sockfd, (struct sockaddr*)&client_sock,&len);
  65. }
  66. }
  67. }
  68. /*!
  69. \brief initialize the tcp_client application
  70. \param[in] none
  71. \param[out] none
  72. \retval none
  73. */
  74. void tcp_server_init(void)
  75. {
  76. xTaskCreate(tcp_server_task, "TCP_CLIENT", DEFAULT_THREAD_STACKSIZE, NULL, 4, NULL);
  77. }