开始可以根据附带的test程序学习。不过里面有一些小地方要稍加注意,这里主要讲read_cb时对方断开的处理:
在blackhole-server.c有如下语句:
static void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
conn_rec* conn;
int r;
if (nread >= 0)
return;
ASSERT(nread == UV_EOF);
conn = container_of(stream, conn_rec, handle);
r = uv_shutdown(&conn->shutdown_req, stream, shutdown_cb);
ASSERT(r == 0);
}
代码很简单,nread<0时shutdown socket。不过这时容易引起异常:当对方主动断开,或网络故障断开时,libuv会出一个异常,大致意思是,此处不应该用shutdown,而是直接close。
此处可以参考test-tcp-write-to-half-open-connection.c:
static void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
if (nread < 0) {
fprintf(stderr, "read_cb error: %s\n", uv_err_name(nread));
ASSERT(nread == UV_ECONNRESET || nread == UV_EOF);
uv_close((uv_handle_t*)&tcp_server, NULL);
uv_close((uv_handle_t*)&tcp_peer, NULL);
}
read_cb_called++;
}
在其他的test里也是用的close,比如test-tcp-writealot.c,test-tcp-write-to-half-open-connection.c,benchmark-pound.c等 等。
好象只有blackhole-server.c这里面用shutdown了,主要是和演示的功能有关。
有朋友问libuv怎么用,随手就把blackhole-server这个例子拿出来。不过使用中发现经常有异常,跟踪一下发现了这个问题。看代码还是要更细心一些,暂记。