套接字连接超时10060

时间:2017-04-14 03:16:39

标签: c++ windows winsock

基本上我有一个绑定到某个IP地址和端口的套接字服务器

这是代码

#include "stdafx.h"
#include "Winsock.h"

Winsock* Winsock::_Local;
Winsock::Winsock(std::string Socket_Name)
{
    this->Name = Socket_Name;
    InitializeSocket();
}

Winsock::~Winsock(void)
{
}

BOOL Winsock::InitializeSocket()
{


    //Initialize socket support WINDOWS ONLY!
    SocketConnected = true;
    unsigned short wVersionRequested; WSADATA wsaData; int err;
    wVersionRequested = MAKEWORD( 2, 2 );
    err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 || ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ))
    {
        Console_WriteLine("Could not find useable sock dll %u ", WSAGetLastError());
        return FALSE;
    }

    //Initialize sockets and set any options

    hsock = socket(AF_INET, SOCK_STREAM, 6);
    if(hsock == -1)
    {
        Console_WriteLine("Error initializing socket %u ", WSAGetLastError());
        return FALSE;
    }

    p_int = (int*)malloc(sizeof(int)); *p_int = 1;
    if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
        (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) )
    {
        Console_WriteLine("Error setting socket options %u ", WSAGetLastError());
        free(p_int);
        return FALSE;
    }
    free(p_int);
    _Local = this;
    return TRUE;
}

int Winsock::Connect(int Port, string IP)
{
    struct sockaddr_in my_addr;
    my_addr.sin_family = AF_INET ;
    my_addr.sin_port = htons(Port);

    memset(&(my_addr.sin_zero), 0, 8);
    my_addr.sin_addr.s_addr = inet_addr(IP.c_str());

    if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == SOCKET_ERROR )
    {
        Console_WriteLine("Error connecting socket %u ", WSAGetLastError());
        return WSAGetLastError();
    }
    SocketConnected = true;
    return TRUE;
}

int Winsock::Listen(int Port, string IP)
{
    struct sockaddr_in my_addr;

    my_addr.sin_family = AF_INET ;
    my_addr.sin_port = htons(Port);

    memset(&(my_addr.sin_zero), 0, 8);
    if (IP == "")
        my_addr.sin_addr.s_addr = INADDR_ANY;
    else
        my_addr.sin_addr.s_addr = inet_addr(IP.c_str());

    Console_WriteLine("binding socket... Port: %d IP: %s", Port, IP.c_str());
    if( bind( hsock, (SOCKADDR*)&my_addr, sizeof(my_addr)) == -1 )
    {
        Console_WriteLine("Error binding to socket, make sure nothing else is listening on this port %d ",WSAGetLastError());
        return WSAGetLastError();
    }
    if(listen( hsock, 10) == -1 )
    {
        Console_WriteLine("Error listening %d ",WSAGetLastError());
        return WSAGetLastError();
    }
    return TRUE;
}

void Winsock::BeginAccept(void(WINAPI *Callback)(int*))
{
    CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Run_BeginAccept, Callback, 0, 0);
}

void WINAPI Winsock::_BeginAccept(void(WINAPI *Callback)(int*))
{
    int* csock;
    sockaddr_in sadr;
    int addr_size = sizeof(SOCKADDR);
    int i = 0;

    while (true)
    {
        i++;
        csock = (int*)malloc(sizeof(int));

        if ((*csock = accept(hsock, (SOCKADDR*)&sadr, &addr_size)) != INVALID_SOCKET)
        {
            Callback(csock);
        }
        else
        {
            Console_WriteLine("Error accepting closing socket.. Error ID: %d", WSAGetLastError());
            ShutDown();
            break;
        }
    }
}

void Winsock::Send(char* Data, int Lenght)
{
    int iResult = send(hsock, Data, Lenght, 0);
    if (iResult == SOCKET_ERROR)
    {
        Console_WriteLine("send failed Data AsServer %u ", WSAGetLastError());
        closesocket(hsock);
        WSACleanup();
    }
}

void Winsock::ShutDown()
{
    if (!SocketConnected) return;
    int iResult = shutdown(hsock, 2);
    if (iResult == SOCKET_ERROR)
    {
        Console_WriteLine("shutdown failed: %u ", WSAGetLastError());
        closesocket(hsock);
        WSACleanup();

    }
    SocketConnected = false;
}

函数Run_BeginAccept

static DWORD Run_BeginAccept(void(WINAPI *Callback)(int*))
    {

        _Local->_BeginAccept(Callback);

        return 0;
    }

这是实现

    Winsock* Socket = new Winsock("Local Socket");
    Socket->Listen(1101, "127.0.0.1");
    Socket->BeginAccept(Process_Accept);

Process_Accept

void __stdcall Process_Accept(int* Socket)
{
    Console_WriteLine("Incoming connection... socket: %u", Socket);
}

这是客户端

#include "Winsock.h"

Winsock* Winsock::_Local;

Winsock::Winsock(std::string Socket_Name)
{
    this->Name = Socket_Name;
    InitializeSocket();
}

Winsock::~Winsock(void)
{
}

BOOL Winsock::InitializeSocket()
{
    //Initialize socket support WINDOWS ONLY!
    SocketConnected = true;
    WORD wVersionRequested; WSADATA wsaData; int err;
    wVersionRequested = MAKEWORD( 2, 2 );
    err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 || ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ))
    {
        Console_WriteLine("Could not find useable sock dll %u ", WSAGetLastError());
        return FALSE;
    }

    //Initialize sockets and set any options

    hsock = socket(AF_INET, SOCK_STREAM, 6);
    if(hsock == -1)
    {
        Console_WriteLine("Error initializing socket %u ", WSAGetLastError());
        return FALSE;
    }

    p_int = (int*)malloc(sizeof(int)); *p_int = 1;
    if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
        (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) )
    {
        Console_WriteLine("Error setting socket options %u ", WSAGetLastError());
        free(p_int);
        return FALSE;
    }
    free(p_int);
    _Local = this;
    Connect(1101, "127.0.0.1");
    return TRUE;
}

int Winsock::Connect(int Port, string IP)
{
    struct sockaddr_in my_addr;
    my_addr.sin_family = AF_INET ;
    my_addr.sin_port = htons(Port);

    memset(&(my_addr.sin_zero), 0, 8);
    my_addr.sin_addr.s_addr =inet_addr(IP.c_str());

    if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == SOCKET_ERROR )
    {
        Console_WriteLine("Error connecting socket %u ", WSAGetLastError());
        return WSAGetLastError();
    }
    SocketConnected = true;
    return TRUE;
}

void Winsock::BeginReceive(CBClient * Client)
{
    CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Run_BeginReceive, Client, 0, 0);
}

void Winsock::_BeginReceive(CBClient * Client)
{
    int recvbuflen = DEFAULT_BUFLEN; char Buffer[DEFAULT_BUFLEN];
    int TLength;
    do {

        memset(Buffer, 0, recvbuflen);
        TLength = recv(hsock, Buffer, recvbuflen, 0);
        if (TLength > 0)
        {
            Client->Localsocket_Onreceive(Buffer, TLength);
        }
        else if (TLength == 0)
        {
            Console_WriteLine("%s Connection closed", this->Name.c_str());
            SocketConnected = false;
            ShutDown();
        }
        else
        {
            SocketConnected = false;
            ShutDown();
            break;
        }
    } while (TLength > 0);
}

void Winsock::Send(char* Data, int Lenght)
{
    int iResult = send(hsock, Data, Lenght, 0);
    if (iResult == SOCKET_ERROR)
    {
        Console_WriteLine("send failed Data AsServer %u ", WSAGetLastError());
        closesocket(hsock);
        WSACleanup();
    }
}

void Winsock::ShutDown()
{
    if (!SocketConnected) return;
    int iResult = shutdown(hsock, 2);
    if (iResult == SOCKET_ERROR)
    {
        Console_WriteLine("shutdown failed: %u ", WSAGetLastError());
        closesocket(hsock);
        WSACleanup();

    }
    SocketConnected = false;
}

现在服务器初始化成功,但每当我尝试连接时 使用客户端我得到超时错误10060。

我已禁用防火墙并打开端口,但我似乎无法找到 它没有连接的原因。

我在某处看到客户端停止连接,因为它没有从服务器收到答案,但是因为服务器甚至没有对尝试的连接做出反应。

谢谢你的时间。

0 个答案:

没有答案