TcpEchoServer.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /********************************************************************************
  2. * File Name: TcpEchoServer.c
  3. * Function Describe:Echo Server by TCP
  4. * Relate Module:
  5. * Explain:
  6. * Writer: slw
  7. * Date:
  8. *******************************************************************************/
  9. #include "includes.h"
  10. #include "socket.h"
  11. /**
  12. * @brief Loopback Test Example Code using ioLibrary_BSD
  13. * @retval None
  14. */
  15. int32_t loopback_tcps(uint8_t sn, uint8_t* buf,uint16_t buflen, uint16_t port)
  16. {
  17. char tacebuf[100];
  18. int32_t ret;
  19. uint16_t size = 0, sentsize=0;
  20. switch(getSn_SR(sn))
  21. {
  22. case SOCK_ESTABLISHED :
  23. if(getSn_IR(sn) & Sn_IR_CON)
  24. {
  25. snprintf(tacebuf,sizeof(tacebuf),"%d:Connected\r\n",sn);
  26. SlwTrace(DEBUG,tacebuf);
  27. setSn_IR(sn,Sn_IR_CON);
  28. }
  29. if((size = getSn_RX_RSR(sn)) > 0)
  30. {
  31. if(size > buflen) size = buflen;
  32. ret = recv(sn,buf,size);
  33. if(ret <= 0) return ret;
  34. sentsize = 0;
  35. while(size != sentsize)
  36. {
  37. ret = send(sn,buf+sentsize,size-sentsize);
  38. if(ret < 0)
  39. {
  40. close(sn);
  41. return ret;
  42. }
  43. sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
  44. }
  45. }
  46. break;
  47. case SOCK_CLOSE_WAIT :
  48. snprintf(tacebuf,sizeof(tacebuf),"%d:CloseWait\r\n",sn);
  49. SlwTrace(DEBUG,tacebuf);
  50. if((ret=disconnect(sn)) != SOCK_OK) return ret;
  51. snprintf(tacebuf,sizeof(tacebuf),"%d:Closed\r\n",sn);
  52. SlwTrace(DEBUG,tacebuf);
  53. break;
  54. case SOCK_INIT :
  55. snprintf(tacebuf,sizeof(tacebuf),"%d:Listen, port [%d]\r\n",sn, port);
  56. SlwTrace(DEBUG,tacebuf);
  57. if( (ret = listen(sn)) != SOCK_OK) return ret;
  58. break;
  59. case SOCK_CLOSED:
  60. snprintf(tacebuf,sizeof(tacebuf),"%d:LBTStart\r\n",sn);
  61. SlwTrace(DEBUG,tacebuf);
  62. if((ret=socket(sn,Sn_MR_TCP,port,0x00)) != sn)
  63. return ret;
  64. snprintf(tacebuf,sizeof(tacebuf),"%d:Opened\r\n",sn);
  65. SlwTrace(DEBUG,tacebuf);
  66. break;
  67. default:
  68. break;
  69. }
  70. return 1;
  71. }