CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2014
    Posts
    1

    Sending chat messages across different computers?

    Okay, i made a chat program with immense help from the msdn pages on winsock2. right now im not actually sending any messages with it, but hey its connecting so thats something. but it only connects when i run server and client both on the same computer. How do i establish the connection on not only other computers on my network, but also on other networks (without port forwarding/mapping)? Thank you in advance.

    server:
    Code:
    #include <winsock2.h>
    #include <stdio.h>
    #include <windows.h>
    #define _WIN32_WINNT 0x501
    #include <ws2tcpip.h>
    
    #define DEFAULT_PORT "2001"
    #define DEFAULT_BUFLEN 512
    
    int main()
    {
    WSADATA wsaData;
    
    int iResult;
    
    //initialize winsock
    
    iResult=WSAStartup(MAKEWORD(2,1), &wsaData);
    if (iResult!=0)
    {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }
    
    
    
    struct addrinfo *result=NULL, *ptr=NULL, hints;
    
    ZeroMemory(&hints, sizeof (hints));
    hints.ai_family=AF_INET;
    hints.ai_socktype=SOCK_STREAM;
    hints.ai_protocol=IPPROTO_TCP;
    
    iResult=getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
        if (iResult!=0)
        {
            printf("getaddrinfo failed: %d\n", iResult);
            WSACleanup();
            return 1;
    
        }
    
    
    
    
    //creating the socket
    
    SOCKET ListenSocket=INVALID_SOCKET;
    ListenSocket=socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    
    //error reporting-socket created successfully?
    
        if (ListenSocket==INVALID_SOCKET)
        {
            printf("Error at socket(): %ld\n", WSAGetLastError());
            freeaddrinfo(result);
            WSACleanup();
            return 1;
        }
    
    
    
    //binding the socket to the network ie making it visible to client
    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); //no longer needed. it is already bound with the info
    
    
    
    //listening for client
    if (listen(ListenSocket, SOMAXCONN)==SOCKET_ERROR)
    {
        printf("listen failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    
    //temp socket to accept discovered connections
    SOCKET ClientSocket;
    ClientSocket=INVALID_SOCKET;
    
    ClientSocket=accept(ListenSocket, NULL, NULL); //passing the connection from listenSocket to CLientSocket to be handled
    if (ClientSocket==INVALID_SOCKET)
    {
        printf("accept failed on client socket: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    
    //send/recv
    //def buflen is 512 remember
    
    char recvbuf[DEFAULT_BUFLEN];
    int iSendResult; //took out iResult, it was a redeclaration
    int recvbuflen=DEFAULT_BUFLEN; //should send/recv be a separate f(x)?
    
    do {
    
        iResult=recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult>0)
        {
            printf("bytes received: %d\n", iResult);
    
        //echoing the message being received back to the sender
        iSendResult=send(ClientSocket, recvbuf, iResult, 0);
            if (iSendResult==SOCKET_ERROR)
            {
                printf("send (echo) failed: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
        printf("bytes sent: %d\n", iSendResult);
    
        }
        else if (iResult==0)
        {
            printf("connection closing...\n");
        }
        else
        {
            printf("recv failed: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }
    }
    
    while (iResult>0);
    
    
    
    //breaking the connection and closing the socket
    iResult=shutdown(ClientSocket, SD_SEND);
    if (iResult==SOCKET_ERROR)
    {
        printf("shutdown failed: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }
    closesocket(ClientSocket);
    WSACleanup();
    return 0;
    }
    client:
    Code:
    #include <winsock2.h>
    #include <stdio.h>
    #include <windows.h>
    #define _WIN32_WINNT 0x501
    #include <ws2tcpip.h>
    #pragma comment(lib, "Mswsock.lib")
    #pragma comment(lib, "AdvApi32.lib")
    
    #define DEFAULT_PORT "2001"
    #define DEFAULT_BUFLEN 512
    
    
    int main()
    {
    
    WSADATA wsaData;
    
    int iResult;
    
    //initialize winsock
    
    iResult=WSAStartup(MAKEWORD(2,1), &wsaData);
    if (iResult!=0)
    {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }
    
    
    
    
        struct addrinfo *result=NULL, *ptr=NULL, hints;
        ZeroMemory(&hints, sizeof(hints));
        hints.ai_family=AF_UNSPEC;
        hints.ai_socktype=SOCK_STREAM;
        hints.ai_protocol=IPPROTO_TCP;
    
    //find server address and port
    
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); //wasnt originally null, it was "argv[1]"
    if (iResult != 0) {
        printf("getaddrinfo failed: %d\n", iResult);
        WSACleanup();
        return 1;
    }
    
    //create socket
    SOCKET ConnectSocket=INVALID_SOCKET;
    
    //connect to ip ehhhh
    for (ptr=result;ptr!=NULL;ptr=ptr->ai_next)
    {
        ConnectSocket=socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
    
    
        if (ConnectSocket == INVALID_SOCKET) {
            printf("Error at socket(): %ld\n", WSAGetLastError());
            freeaddrinfo(result);
            WSACleanup();
            return 1;
        }
    
    //connecting----------------------
    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;
    }
    
    
    //send/recv-------------------------
    
    int recvbuflen=DEFAULT_BUFLEN;
    char *sendbuf="this is a test";
    char recvbuf[DEFAULT_BUFLEN];
    
    iResult=send(ConnectSocket, sendbuf, (int) strlen(sendbuf), 0);
    
    if (iResult == SOCKET_ERROR) {
        printf("send failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }
    
    printf("bytes sent: %ld\n", iResult);
    
    //shutdown
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }
    
    //still have to receive data, even though we cant send it any longer. this iwll continue until the server disconnects,
    //which will happen once it is doing echoing the client's message usually
    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: %d\n", WSAGetLastError());
    } while (iResult > 0);
    
    
    closesocket(ConnectSocket);
    WSACleanup();
    return 0;
    
    }

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,395

    Re: Sending chat messages across different computers?

    1. WHat is the socket address the client tries to connect to? Is it the correct address of the server?
    2. Is the firewall on? Is the used socket port enabled?
    Victor Nijegorodov

  3. #3
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    Re: Sending chat messages across different computers?

    It looks like your server is only listening on "127.0.0.1". You need to listen on any available address, or at least on a network address reachable from the outside.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured