Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

windows平台tb_socket_recv返回值问题 #154

Open
zt449569708 opened this issue Nov 15, 2020 · 3 comments
Open

windows平台tb_socket_recv返回值问题 #154

zt449569708 opened this issue Nov 15, 2020 · 3 comments

Comments

@zt449569708
Copy link

`tb_long_t tb_socket_recv(tb_socket_ref_t sock, tb_byte_t* data, tb_size_t size)
{
// check
tb_assert_and_check_return_val(sock && data, -1);
tb_check_return_val(size, 0);

#ifndef TB_CONFIG_MICRO_ENABLE
// attempt to use iocp object to recv data if exists
tb_iocp_object_ref_t iocp_object = tb_iocp_object_get_or_new_from_sock(sock, TB_POLLER_EVENT_RECV);
if (iocp_object) return tb_iocp_object_recv(iocp_object, data, size);
#endif

// recv
tb_long_t real = tb_ws2_32()->recv(tb_sock2fd(sock), (tb_char_t*)data, (tb_int_t)size, 0);

// ok?
if (real >= 0) return real;

// errno
tb_long_t e = tb_ws2_32()->WSAGetLastError();

// continue?
if (e == WSAEWOULDBLOCK || e == WSAEINPROGRESS) return 0;

// error
return -1;

}`
问题描述:
在windows下,建立了tcp server和client,但是client正常关闭的时候,导致server无法判断client是否关闭。因为对于windows的recv函数,如果对端是正常关闭,返回值也为0(出自windows API原文:If no error occurs, recv returns the number of bytes received and the buffer pointed to by the buf parameter will contain this data received. If the connection has been gracefully closed, the return value is zero.),而现在这种情况 if (e == WSAEWOULDBLOCK || e == WSAEINPROGRESS) return 0; 也是返回0。

@waruqi
Copy link
Member

waruqi commented Nov 15, 2020

关闭检测要走wait + recv 配合,才能跨平台通用

请参考

tb_bool_t tb_socket_brecv(tb_socket_ref_t sock, tb_byte_t* data, tb_size_t size)
{
// recv data
tb_size_t recv = 0;
tb_long_t wait = 0;
while (recv < size)
{
// recv it
tb_long_t real = tb_socket_recv(sock, data + recv, size - recv);
// has data?
if (real > 0)
{
recv += real;
wait = 0;
}
// no data? wait it
else if (!real && !wait)
{
// wait it
wait = tb_socket_wait(sock, TB_SOCKET_EVENT_RECV, -1);
tb_check_break(wait > 0);
}
// failed or end?
else break;
}
return recv == size;
}

@zt449569708
Copy link
Author

zt449569708 commented Nov 17, 2020 via email

@waruqi
Copy link
Member

waruqi commented Nov 17, 2020

是的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants