Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

[C/C++]Winsock 2 Tutorial For Beginners

Legendary Battlemage
Loyal Member
Joined
Apr 7, 2009
Messages
647
Reaction score
25
What is Winsock?
WinSock is the default Windows socket/network library.

Prerequisites:
Windows with WinSock 2
Visual Studio/Visual C++
Basic Knowledge of Unmanaged C++

Tutorial One: Humble Beginnings
In this tutorial we will cover:
  • Initializing WinSock
  • Creating a Socket
  • Connecting/Listening on the Socket
  • Create a simple client/server message sender

First, create an empty CLR project called "WinSockMSGSender".
Now, you will need to include the necessary libraries for WinSock. Go to Project > WinSockMSGSender Properties > Configuration Properties > Linker.

Click on "Additional Dependencies", then click the "..." button.

Now type in ws2_32.lib.
ws2_32.lib is our WinSock v2 library.

Now, you're all set to start programming WinSock.

Part 1: The Client

Your project WAS empty, right?

Right click on "Header Files", and add a header file called Program.

Do the same for "Source Files", but make a CPP file.

#region Header File
In the header file, input the following:

PHP:
#define WIN32_LEAN_AND_MEAN

#define SERVERIP "127.0.0.1"

#define PORT "9999"

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>

Now, you might already know this, but I'll explain.

Defining WIN32_LEAN_AND_MEAN will exclude rarely used stuff.
We'll be defining the port we listen on by using #define PORT and setting port to 9999.
Including Windows, winsock2, and ws2tcpip...that's obvious. If you can't figure this out, please stop reading this tutorial. :p

Anyways, now we've set up our header file's header. (try saying that 5 times fast)

Now to declare our function.

Skip a line, and add

PHP:
class WSMT
{
public:
     static int InitConns();
};

Now save.

Time for our CPP file, where we will define our function!
#ENDREGION
#REGION CPP File
Open your CPP file.

In it, type

PHP:
#include "Program.h"

int WSMT::InitConns()
{
     
}

NOTICE:
From this point on, until you see "/In Function", all code will go in side the curly braces of the InitConns() function.

Now that we've defined our function, let's fill 'er up! (please get your mind out of the gutter if you are thinking dirty thoughts. Thank you.)

First, we'll define our WSAData variable, which will contain all WinSock data, such as the version.

PHP:
WSAData wsaData;

Now, we'll define a result variable, to test for success.

PHP:
int iResult;

Now, let's initialize our variables!

PHP:
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);

Now we'll check for any WSAStartup errors, and if any occur, we exit.

From this point on, you'll see iResult as the error checker.
Many of the WS functions are int functions, so they return a 0 on success, otherwise we have a problem.
PHP:
if(iResult != 0)
{
     printf("LMAO FAIL.");//How could we fail on starting up?  version error? idk. O_O
     return 1;
}

And now, assuming everything went dandy, we initialize the address info
PHP:
	struct addrinfo *tresult = NULL,
				*tptr = NULL,
				thints;

And now we zero the memory (you could also use memset, but I prefer ZeroMemory-it's faster. :p)...
PHP:
	ZeroMemory( &thints, sizeof(thints) );

And now, assign properties...
PHP:
	thints.ai_family = AF_UNSPEC;
	thints.ai_socktype = SOCK_STREAM;
	thints.ai_protocol = IPPROTO_TCP;//We'll be using TCP... change it to IPPROTO_UDP if you wish.

Now, we're getting to the exciting stuff!
Let's initialize our socket:
PHP:
SOCKET ConnSock = INVALID_SOCKET

Now, let's get the address info of our desired host.
Again, we'll be using the return value of the WS function to determine a success or not.
PHP:
iResult = getaddrinfo(SERVERIP, PORT, &thints, &tresult);

If nothing failed, we'll move on.
We'll set the ptr as the result, and actually initialize the socket.

However, if it failed, we'll cleanup the mess we made with the function WSACleanup(), and return 1.
PHP:
if(iResult != 0)
{
     printf("WTF WE FAILED.");//getaddrinfo has failed.  Check the info
     WSACleanup();
     return 1;
}

tptr = tresult;

ConnSock = socket(tptr->ai_family, tptr->ai_socktype, tptr->ai_protocol);

Yes! Now all we need to do is check for an error, and connect!

Notice that we don't use iResult this time.
This is because ConnSock can have a value of INVALID_SOCKET, which is predefined as an int value.
PHP:
if(ConnSock == INVALID_SOCKET)
{
     printf("LOLOMG FAIL.");
     WSACleanup();
     return 1;
}

iResult = connect(ConnSock, tptr->ai_addr, (int)tptr->ai_addrlen);

You didn't think we'd forget to check iResult for an error, did you? :p

PHP:
if(iResult == SOCKET_ERROR)//Again, SOCKET_ERROR is a predefiend integer value.
{
     closesocket(ConnSock);//Close our socket
     ConnSock = INVALID_SOCKET;//Since we failed, we better set this to invalid, so we can cleanup later.
}

Notice that we don't call WSACleanup(), because we have more cleaning up to do.

PHP:
freeaddrinfo(tresult);//Free the address info

if(ConnSock == INVALID_SOCKET)//Well, if it was an error, it has to be INVALID_SOCKET, cuz we set it...
{
     printf("LOLFAILWEWASSOCLOSE");//So the only way we could have got here would be failing on the connection...
     WSACleanup();
     return 1;
}

But otherwise...that must mean the connection succeeded!

PHP:
while(true)
{
     printf("WE IZ CONNECTED.  WE IZ AWESOME!!!");
}

return 0;

Congratz! You've just...oh wait. I still haven't taught you the server yet. :p
Oh well, use the time in between to study up some more!

/In Function
#ENDREGION
 
Last edited:
Skilled Illusionist
Joined
Apr 22, 2009
Messages
301
Reaction score
19
Your tutorial quality is improving, but there is still alot of incorrect definitions, and your class is just not used, I mean theres no point writing a class if you use it like that.
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
Your error messages should explain, why the error occurred.. IMO


Also, I didn't learn anything from this. I've never sent/received a socket, and this tutorial may help me copy+paste, but it doesn't teach me much of anything that I didn't already know about sockets. I know you need a port, If it failed, I wouldn't know why, other than "LOLFAILWEWASSOCLOSE", and if I did somehow manage to get it working, then all I would know is "WE IZ CONNECTED. WE IZ AWESOME!!!".. I guess I would be "AWESOME!!!", but I wouldn't even know why, or what to do with the sockets from there...

Love the attitude though, good stuff! ;)
 
Legendary Battlemage
Loyal Member
Joined
Apr 7, 2009
Messages
647
Reaction score
25
Your error messages should explain, why the error occurred.. IMO


Also, I didn't learn anything from this. I've never sent/received a socket, and this tutorial may help me copy+paste, but it doesn't teach me much of anything that I didn't already know about sockets. I know you need a port, If it failed, I wouldn't know why, other than "LOLFAILWEWASSOCLOSE", and if I did somehow manage to get it working, then all I would know is "WE IZ CONNECTED. WE IZ AWESOME!!!".. I guess I would be "AWESOME!!!", but I wouldn't even know why, or what to do with the sockets from there...

Love the attitude though, good stuff! ;)

Thanks, I think i'll add in error descriptions now. :)
 
Junior Spellweaver
Joined
Feb 14, 2007
Messages
106
Reaction score
0
I'm so trying this out tomorrow! ^^
 
Back
Top