如何在WinSock2中使用绑定功能?

时间:2019-05-25 20:36:12

标签: c++ winsock2

我正在做一个多线程服务器,为了做到这一点,我需要在“ winsock2.h”中使用函数“ bind”,但是不知何故,编译器选择使用甚至在winsock2中也不使用的未知绑定函数。H。 我该如何选择要使用的功能?

//the bind function that i dont wanna use
template <class _Fx, class... _Types>
_NODISCARD inline _Binder<_Unforced, _Fx, _Types...> bind(
    _Fx&& _Func, _Types&&... _Args) { // bind a callable object with an implicit return type
    return _Binder<_Unforced, _Fx, _Types...>(_STD forward<_Fx>(_Func), _STD forward<_Types>(_Args)...);
}


//the winsock2 function i wanna use
int
WSAAPI
bind(
    _In_ SOCKET s,
    _In_reads_bytes_(namelen) const struct sockaddr FAR * name,
    _In_ int namelen
    );


//my code
void Communicator::bindAndListen()
{
    struct sockaddr_in sa = { 0 };

    sa.sin_port = htons(PORT); // port that server will listen for
    sa.sin_family = AF_INET;   
    sa.sin_addr.s_addr = INADDR_ANY;  

    if (bind(serverSocket, (struct sockaddr*)& sa, sizeof(sa)) == SOCKET_ERROR)
        throw std::exception(__FUNCTION__ " - bind");


    if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR)
        throw std::exception(__FUNCTION__ " - listen");

    std::cout << "Listening on port " << PORT << std::endl;

    while (true)
    {
        std::cout << "Waiting for clients" << std::endl;
        accept();
    }
}

0 个答案:

没有答案