Thrift发送中断处理
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thrift发送中断处理相关的知识,希望对你有一定的参考价值。
场景分析当客户端异常断开连接,但是这个时候服务器并不知道连接已经失效,服务端这个时候尝试发送数据给客户端,这个时候就会触发中断,抛出异常
先分析一下服务器发送数据的函数
void TSocket::write(const uint8_t* buf, uint32_t len) {
uint32_t sent = 0;
while (sent < len) {
uint32_t b = write_partial(buf + sent, len - sent);
if (b == 0) {
// This should only happen if the timeout set with SO_SNDTIMEO expired.
// Raise an exception.
throw TTransportException(TTransportException::TIMED_OUT,
"send timeout expired");
}
sent += b;
}
}
但b==0抛出异常,代表当前发送超时。while循环是为了循环发送,因为一次不一定发送完用户数据,毕竟MTU的限制。注意sent是一个无符号整型,当b返回-1的时候,sent==0-1意味着将达到32位整数最大值,大于len,从而直接退出循环。因为套接字已经中断,所以发送失败,在调用write_partial函数的时候,返回b ==-1,导致退出循环,从而避免了抛出异常,因此返回-1,是非常合理的值
uint32_t TSocket::write_partial(const uint8_t* buf, uint32_t len) {
if (socket_ == -1) {
return -1;
throw TTransportException(TTransportException::NOT_OPEN, "Called write on non-open socket");
}
uint32_t sent = 0;
int flags = 0;
#ifdef MSG_NOSIGNAL
// Note the use of MSG_NOSIGNAL to suppress SIGPIPE errors, instead we
// check for the EPIPE return condition and close the socket in that case
flags |= MSG_NOSIGNAL;
#endif // ifdef MSG_NOSIGNAL
int b = send(socket_, const_cast_sockopt(buf + sent), len - sent, flags);
++g_socket_syscalls;
if (b < 0) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
return 0;
}
// Fail on a send error
int errno_copy = errno;
GlobalOutput.perror("TSocket::write_partial() send() " + getSocketInfo(), errno_copy);
if (errno_copy == EPIPE || errno_copy == ECONNRESET || errno_copy == ENOTCONN) {
close();
return -1;
//throw TTransportException(TTransportException::NOT_OPEN, "write() send()", errno_copy);
}
close();
return -1;
throw TTransportException(TTransportException::UNKNOWN, "write() send()", errno_copy);
}
// Fail on blocked send
if (b == 0) {
throw TTransportException(TTransportException::NOT_OPEN, "Socket send returned 0.");
}
return b;
}
以上是关于Thrift发送中断处理的主要内容,如果未能解决你的问题,请参考以下文章