CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  1. #1
    Join Date
    Dec 2017
    Posts
    41

    Winsock API - send an receive data simultaneously

    I'm using winsock api to create a program that can send and receive data between two users. What I tried so far doesn't work:


    Code:
    #pragma comment(lib,"ws2_32.lib")
    #include <WinSock2.h>
    #include <iostream>
    
    int main()
    {
    	//WinSock Startup
    	WSAData wsaData;
    	WORD DllVersion = MAKEWORD(2, 1);
    	if (WSAStartup(DllVersion, &wsaData) != 0) //If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup.
    	{
    		MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);
    		return 0;
    	}
    
    
    
    	SOCKADDR_IN addr; //Address that we will bind our listening socket to
    	int addrlen = sizeof(addr); //length of the address (required for accept call)
    	addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //Broadcast locally
    	addr.sin_port = htons(1111); //Port
    	addr.sin_family = AF_INET; //IPv4 Socket
    
    
    
    	SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL); //Create socket to listen for new connections
    	bind(sListen, (SOCKADDR*)&addr, sizeof(addr)); //Bind the address to the socket
    	listen(sListen, SOMAXCONN); //Places sListen socket in a state in which it is listening for an incoming connection. Note:SOMAXCONN = Socket Oustanding Max Connections
    
    
    
    	SOCKET newConnection; //Socket to hold the client's connection
    	newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen); //Accept a new connection
    	if (newConnection == 0) //If accepting the client connection failed
    	{
    		std::cout << "Failed to accept the client's connection." << std::endl;
    	}
    	else //If client connection properly accepted
    	{
            std::cout << "Client Connected!" << std::endl;
    	   while (true){
    
                char a[256] = {};
                std::cin >> a;
                send(newConnection, a, sizeof(a), NULL);
    
    			char MOTD[256];
                recv(newConnection, MOTD, sizeof(MOTD), NULL); //Receive Message of the Day buffer into MOTD array
                std::cout << "MOTD:" << MOTD << std::endl;
            }
    	}
    
    	system("pause");
    	return 0;
    }
    Also is there a way for my program to work as a web server, to get data using a web browser?

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

    Re: Winsock API - send an receive data simultaneously

    Quote Originally Posted by binary2 View Post
    I'm using winsock api to create a program that can send and receive data between two users. What I tried so far doesn't work:
    Could you provide more information about what exactly doesn't work?
    Victor Nijegorodov

  3. #3
    Join Date
    Dec 2017
    Posts
    41

    Re: Winsock API - send an receive data simultaneously

    I'm trying to build a client and a server in the same program. For example, user 1 sends a packet of data to user 2, user 2 after receiving the packet sends back a different packet to user 1. The problem is, after running the program neither user receives the packets.

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

    Re: Winsock API - send an receive data simultaneously

    Quote Originally Posted by binary2 View Post
    I'm trying to build a client and a server in the same program. For example, user 1 sends a packet of data to user 2, user 2 after receiving the packet sends back a different packet to user 1. The problem is, after running the program neither user receives the packets.
    Did you debug your server code?
    Does it receive anything? If yes - is it exactly what the client sent?
    Victor Nijegorodov

  5. #5
    Join Date
    Dec 2017
    Posts
    41

    Re: Winsock API - send an receive data simultaneously

    I tried with the server and client separated in 2 console programs and it worked. So the connection part is good.
    I thing my problem is in the while loop here:

    Code:
    SOCKET newConnection; //Socket to hold the client's connection
    	newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen); //Accept a new connection
    	if (newConnection == 0) //If accepting the client connection failed
    	{
    		std::cout << "Failed to accept the client's connection." << std::endl;
    	}
    	else //If client connection properly accepted
    	{
            std::cout << "Client Connected!" << std::endl;
    	   while (true){
    
                char a[256] = {};
                std::cin >> a;
                send(newConnection, a, sizeof(a), NULL);
    
    			char MOTD[256];
                recv(newConnection, MOTD, sizeof(MOTD), NULL); //Receive Message of the Day buffer into MOTD array
                std::cout << "MOTD:" << MOTD << std::endl;
            }
    	}

    Edit:

    I revised the code, I still get an error:
    Code:
    #pragma comment(lib,"ws2_32.lib")
    #include <WinSock2.h>
    #include <iostream>
    
    static char buffer[8096 + 1];
    char a[256] = {};
    char MOTD[256];
    
    int main()
    {
    	//WinSock Startup
    	WSAData wsaData;
    	WORD DllVersion = MAKEWORD(2, 1);
    	if (WSAStartup(DllVersion, &wsaData) != 0) //If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup.
    	{
    		MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);
    		return 0;
    	}
    
    
    
    	SOCKADDR_IN addr; //Address that we will bind our listening socket to
    	int addrlen = sizeof(addr); //length of the address (required for accept call)
    	addr.sin_addr.s_addr = inet_addr(INADDR_ANY); //Broadcast locally
    	addr.sin_port = htons(1111); //Port
    	addr.sin_family = AF_INET; //IPv4 Socket
    
    
    
    
    
    	SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL); //Create socket to listen for new connections
    	bind(sListen, (SOCKADDR*)&addr, sizeof(addr)); //Bind the address to the socket
    	listen(sListen, SOMAXCONN); //Places sListen socket in a state in which it is listening for an incoming connection. Note:SOMAXCONN = Socket Oustanding Max Connections
    
        SOCKET newConnection;
        newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
        if (newConnection == 0){
            std::cout << "Failed to accept the client's connection." << std::endl;
        }else{
            std::cout << "Client Connected!" << std::endl;
        }
    
    
    
        for( int i=0;i< 10;i++ ){
            if (connect(newConnection, (SOCKADDR*)&addr, sizeof(addr)) != 0) //If we are unable to connect...
            {
                MessageBoxA(NULL, "Failed to Connect", "Error", MB_OK | MB_ICONERROR);
                 std::cout << WSAGetLastError();
    
            }else{
                std::cout << 123;
            }
        }
    
    
    
    	  while (true){
    
                std::cin >> a;
                send(newConnection, a, sizeof(a), NULL);
    
    
                recv(newConnection, MOTD, sizeof(MOTD), NULL);
                std::cout << "MOTD:" << MOTD << std::endl;
    	}
    
    	system("pause");
    	return 0;
    }
    Last edited by binary2; July 14th, 2018 at 03:40 PM.

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Winsock API - send an receive data simultaneously

    You'll need to run either the server or the client code in a separate thread. It blocks if you try to run both in the same thread of the process (and is why it works from two different processes).

  7. #7
    Join Date
    Dec 2017
    Posts
    41

    Re: Winsock API - send an receive data simultaneously

    Can you show me an example of how to do that

  8. #8
    Join Date
    Dec 2017
    Posts
    41

    Re: Winsock API - send an receive data simultaneously

    I put the server and client in 2 threads separately, still data is not sent between 2 instances of my program.

    Code:
    #pragma comment(lib,"ws2_32.lib")
    #include <WinSock2.h>
    #include <iostream>
    #include <thread>
    
    static const int num_threads = 2;
    
    static char buffer[8096 + 1];
    char a[256] = {};
    char MOTD[256];
    
    
    void call_from_thread(int tid) {
        if( tid == 0 ){
            //WinSock Startup
            WSAData wsaData;
            WORD DllVersion = MAKEWORD(2, 1);
            if (WSAStartup(DllVersion, &wsaData) != 0){MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);}
    
            SOCKADDR_IN addr;
            int addrlen = sizeof(addr);
            addr.sin_addr.s_addr = inet_addr("127.0.0.1");
            addr.sin_port = htons(1111);
            addr.sin_family = AF_INET;
    
            SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL);
            bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
            listen(sListen, SOMAXCONN);
    
            SOCKET newConnection;
            newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
            if (newConnection == 0){
                std::cout << "Failed to accept the client's connection." << std::endl;
            }else{
                std::cout << "Client Connected!" << std::endl;
            }
    
            while (true){
                std::cin >> a;
                send(newConnection, a, sizeof(a), NULL);
            }
    
        }else if( tid == 1 ){
            //Winsock Startup
            WSAData wsaData;
            WORD DllVersion = MAKEWORD(2, 1);
            if (WSAStartup(DllVersion, &wsaData) != 0){MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);}
    
            SOCKADDR_IN addr;
            int sizeofaddr = sizeof(addr);
            addr.sin_addr.s_addr = inet_addr("127.0.0.1");
            addr.sin_port = htons(1111);
            addr.sin_family = AF_INET;
    
            SOCKET Connection = socket(AF_INET, SOCK_STREAM, NULL); //Set Connection socket
            if (connect(Connection, (SOCKADDR*)&addr, sizeofaddr) != 0) //If we are unable to connect...
            {
                MessageBoxA(NULL, "Failed to Connect", "Error", MB_OK | MB_ICONERROR);
                //return 0; //Failed to Connect
            }
    
            std::cout << "Connected!" << std::endl;
    
            char MOTD[256];
            while (true){
                recv(Connection, MOTD, sizeof(MOTD), NULL); //Receive Message of the Day buffer into MOTD array
                std::cout << "MOTD:" << MOTD << std::endl;
            }
        }
    }
    int main() {
             std::thread t[num_threads];
    
             for (int i = 0; i < num_threads; ++i) {
                 t[i] = std::thread(call_from_thread, i);
             }
    
             for (int i = 0; i < num_threads; ++i) {
                 t[i].join();
             }
    
        return 0;
    }

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