使用c ++ Winsock在一台计算机上使用两个应用程序,但在不同的计算机上不能。

时间:2014-06-18 22:04:29

标签: c++ client winsock

我会发布我的代码,但我不一定需要它。我只是想知道错误是否最有可能与代码,或者我的问题是否是预期的。这是我第一次尝试这个。我刚刚复制了MSDN上发布的Winsock服务器/客户端示例。我已禁用防火墙,但没有帮助。我是否需要查看Port Forwarding之类的内容,或者是否存在影响此功能的设置(getaddrinfo,connect,listen等等),或者当服务器和客户端在两台独立的计算机上运行时理论上是否应该连接应用程序在同一台计算机上运行时连接?

这是我的服务器:

int server(){
WSADATA wsaData;
int iResult;
int i;

SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;

struct addrinfo *result = NULL;
struct addrinfo hints;
char sendbuf[sizeof(me)];

char ip[40];
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
int timer = GetTickCount();

printf("Opening server socket\n");

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed with error: %d\n", iResult);
    return 1;
}

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
    printf("getaddrinfo failed with error: %d\n", iResult);
    WSACleanup();
    return 1;
}

// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
    printf("socket failed with error: %ld\n", WSAGetLastError());
    freeaddrinfo(result);
    WSACleanup();
    return 1;
}

// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
    printf("bind failed with error: %d\n", WSAGetLastError());
    freeaddrinfo(result);
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

freeaddrinfo(result);

iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
    printf("listen failed with error: %d\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

//This part just displays computer hostname and IP address to input in the client
if(gethostname(ip, sizeof(ip))!=0){

    std::cout << "ERROR: " << WSAGetLastError() << std::endl;
}
i=0;
std::cout << "Host name is ";

   struct hostent *phe = gethostbyname(ip);
if (phe == 0) {
    std::cerr << "Yow! Bad host lookup." << std::endl;
    return 1;
}

i=0;
while(ip[i]!=NULL)
    std::cout << ip[i++];



for (i = 0; phe->h_addr_list[i] != 0; ++i) {
    struct in_addr addr;
    memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
    std::cout << "Address " << i << ": " << inet_ntoa(addr) << std::endl;
}


// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
    printf("accept failed with error: %d\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}


// No longer need server socket
closesocket(ListenSocket);


// Receive until the peer shuts down the connection
do{
    while(GetTickCount()-timer<(1000/(2.0*FPS)))
        Sleep(SLEEPTIMER);

    me[0]=cx;
    me[1]=cy;
    me[2]=dr;
    me[3]=at;

    memcpy(sendbuf, me, sizeof(float)*4);
    iResult = send( ClientSocket, sendbuf, sizeof(float)*4, 0 );
    iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
    memcpy(them, recvbuf, sizeof(float)*4);

    std::cout << sizeof(me) << std::endl;

    if (iResult == 0)
        printf("Connection closing...\n");

} while (iResult > 0);

// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
    printf("shutdown failed with error: %d\n", WSAGetLastError());
    closesocket(ClientSocket);
    WSACleanup();
    return 1;
}

// cleanup
closesocket(ClientSocket);
WSACleanup();

return 0;
}

这是我的客户:

int __cdecl client() 
{
printf("Opening clent socket\n");
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
                *ptr = NULL,
                hints;
char sendbuf[sizeof(me)];
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
char *init = "this is a test";
int timer = GetTickCount();

std::string  ip;
PCSTR ip_c;


//window.setFramerateLimit(1);

std::cout << "Enter the IP address of the server: ";
std::cin >> ip;

//memcpy(&ip_c, &ip, sizeof(ip));

/* // Validate the parameters
if (argc != 2) {
    printf("usage: %s server-name\n", argv[0]);
    return 1;
}*/

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed with error: %d\n", iResult);
    return 1;
}

ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

// Resolve the server address and port
iResult = getaddrinfo(ip.c_str(), DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
    printf("getaddrinfo failed with error: %d\n", iResult);
    WSACleanup();
    return 1;
}

// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
    printf("Attempting to connect\n");
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
        ptr->ai_protocol);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    cnct=1;
    printf("Connecting\n");
    std::cout << ptr->ai_addr << std::endl;
    // Connect to server.
    iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        closesocket(ConnectSocket);
        ConnectSocket = INVALID_SOCKET;
        continue;
    }
    break;
}

freeaddrinfo(result);

if (ConnectSocket == INVALID_SOCKET) {
    printf("Unable to connect to server!\n");
    WSACleanup();
    return 1;
}

printf("Sending\n");


// Send an initial buffer
iResult = send( ConnectSocket, init, (int)strlen(init), 0 );
if (iResult == SOCKET_ERROR) {
    printf("send failed with error: %d\n", WSAGetLastError());
    closesocket(ConnectSocket);
    WSACleanup();
    return 1;
}

printf("Bytes Sent: %ld\n", iResult);


while(1){
    while(GetTickCount()-timer<(1000/(2.0*FPS)))
        Sleep(20);

    timer = GetTickCount();

    me[0]=cx;
    me[1]=cy;
    me[2]=dr;
    me[3]=at;

    memcpy(sendbuf, me, sizeof(float)*4);
    iResult = send( ConnectSocket, sendbuf, sizeof(float)*4, 0 );
    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    memcpy(them, recvbuf, sizeof(float)*4);

    std::cout << me[1] << std::endl;


}

// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
    printf("shutdown failed with error: %d\n", WSAGetLastError());
    closesocket(ConnectSocket);
    WSACleanup();
    return 1;
}

// Receive until the peer closes the connection
do {

    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    if ( iResult > 0 )
        printf("Bytes received: %d\n", iResult);
    else if ( iResult == 0 )
        printf("Connection closed\n");
    else
        printf("recv failed with error: %d\n", WSAGetLastError());

} while( iResult > 0 );

// cleanup
closesocket(ConnectSocket);
WSACleanup();

return 0;
}

0 个答案:

没有答案