https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable

http://stackoverflow.com/questions/8874021/close-socket-directly-after-send-unsafe

 

发送端代码

    sock = socket(AF_INET, SOCK_STREAM, 0);  
    connect(sock, &remote, sizeof(remote));
    write(sock, buffer, 1000000);             // returns 1000000
    shutdown(sock, SHUT_WR);
  // 最后这一步要加个超时,防止接收端恶意发送数据 for(;;) { res=read(sock, buffer, 4000); if(res < 0) { perror("reading"); exit(1); } if(!res) break; } close(sock);

这么做的原因是

1. send 成功只是把数据放到了内核的发送缓冲区

2. 当调用 close 时,如果 TCP 的接收缓冲区内有数据,会导致发送 RST(而不是 FIN),并清空发送缓冲区。

 

最好接收端在应用层返回 ack 给发送端。TCP 并不是绝对可靠的

 

相关文章:

  • 2021-10-03
  • 2021-11-02
  • 2022-12-23
  • 2021-07-11
  • 2022-12-23
  • 2022-12-23
  • 2021-08-30
  • 2021-12-10
猜你喜欢
  • 2022-03-04
  • 2022-12-23
  • 2022-12-23
  • 2021-11-24
  • 2022-12-23
  • 2021-11-27
  • 2022-12-23
相关资源
相似解决方案