c++winsockp2pdistributed-computingwinsockets

C++ Winsock P2P


Scenario

Does anyone have any good examples of peer-to-peer (p2p) networking in C++ using Winsock? It's a requirement I have for a client who specifically needs to use this technology (god knows why). I need to determine whether this is feasible.

Any help would be greatly appreciated.

EDIT

And I would like to avoid using libraries so that I can understand the underlying source code and further my knoweldge.


Solution

  • Since I don't know what information you are looking for, I'll try to describe how to set up a socket program and what pitfalls I've run into.

    To start with, *read the Winsock tutorial at MSDN. This is a basic program to connect, send a message and disconnect. It's great for getting a feel for socket programming.

    With that, lets start:

    Considerations:

    Setting up the connection:

    Exchanging data

    In the newSocket you now have a new peer. So that was for receiving data. But note! send is also blocking! One of the head-scratching errors I got was that send blocked me. This was however also solved with select.

     // sending data
     // in: SOCKET sender
     fd_set mySet;
     FD_ZERO(&mySet);
     FD_SET(sender, &mySet);
     timeval zero = { 0, 0 };
     int sel = select(0, NULL, mySet, NULL, &zero);
     if (FD_ISSET(sender, &mySet)){
          // ok to send data
     }
    

    Shutting down

    Finally, there are two ways to shutdown. You either just disconnect by closing your program, or you call the shutdown function.