socket_comm.c 847 B

12345678910111213141516171819202122232425
  1. #include "socket_comm.h"
  2. void
  3. sp_nonblocking(int fd) {
  4. int flag = fcntl(fd, F_GETFL, 0);
  5. if (-1 == flag) {
  6. return;
  7. }
  8. fcntl(fd, F_SETFL, flag | O_NONBLOCK);
  9. }
  10. void
  11. set_keep_alive(int fd) {
  12. //set keep alive
  13. int keepAlive = 1; // 开启keepalive属性
  14. int keepIdle = 60; // 如该连接在60秒内没有任何数据往来,则进行探测
  15. int keepInterval = 5; // 探测时发包的时间间隔为5 秒
  16. int keepCount = 3; // 探测尝试的次数.如果第1次探测包就收到响应了,则后2次的不再发.
  17. setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepAlive, sizeof(keepAlive));
  18. setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, (void*)&keepIdle, sizeof(keepIdle));
  19. setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval));
  20. setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));
  21. }