safe close tcp connection
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 并不是绝对可靠的
+V why_null 请备注:from博客园
浙公网安备 33010602011771号