tcp_server.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include "tcp_server.h"
  4. #include "stm32f2xx.h"
  5. #include "main.h"
  6. #include "log.h"
  7. #include "lwip/tcp.h"
  8. #include "lwip/memp.h"
  9. #include "lwip/api.h"
  10. #include "lwip/sockets.h"
  11. #include "lwip/opt.h"
  12. #include "lwip/sys.h"
  13. void tcp_server_task(void *Parameters)
  14. {
  15. int ret,sockfd;
  16. struct sockaddr_in tcpServerSock;
  17. struct sockaddr_in client_sock;
  18. tcpServerSock.sin_family = AF_INET;
  19. inet_aton("192.168.2.212",&(tcpServerSock.sin_addr));
  20. // tcpServerSock.sin_addr.s_addr = htonl(IPADDR_ANY);
  21. tcpServerSock.sin_port = htons(8080);
  22. tcp_server_begin:
  23. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  24. if (sockfd < 0)
  25. {
  26. goto tcp_server_begin;
  27. }
  28. ret = bind(sockfd, (struct sockaddr *)&tcpServerSock, sizeof(tcpServerSock));
  29. if (ret < 0)
  30. {
  31. lwip_close(sockfd);
  32. sockfd = -1;
  33. goto tcp_server_begin;
  34. }
  35. ret = listen(sockfd, 10);
  36. if (ret < 0)
  37. {
  38. lwip_close(sockfd);
  39. sockfd = -1;
  40. goto tcp_server_begin;
  41. }
  42. while (1)
  43. {
  44. OSTimeDly(1000);
  45. socklen_t len = sizeof(client_sock);
  46. int client_socket = accept(sockfd, (struct sockaddr*)&client_sock,&len);
  47. LogPrint(LOG_INFO,__FILE__,__FUNCTION__,__LINE__,"ÉÏλ»ú³É¹¦Á¬½Ó%s");
  48. if (client_socket<0)
  49. {
  50. printf("error");
  51. }
  52. }
  53. }
  54. /*!
  55. \brief initialize the tcp_client application
  56. \param[in] none
  57. \param[out] none
  58. \retval none
  59. */
  60. #define TCP_TASK_PRIO 9
  61. #define TCP_STK_SIZE 1024
  62. OS_STK TCP_TASK_STK[TCP_STK_SIZE];
  63. void tcp_server_init(void)
  64. {
  65. OSTaskCreate(tcp_server_task,(void*)0,(OS_STK*)&TCP_TASK_STK[TCP_STK_SIZE - 1],TCP_TASK_PRIO);
  66. }