- 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:
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:
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.
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
Now save.
Time for our CPP file, where we will define our function!
#ENDREGION
#REGION CPP File
Open your CPP file.
In it, type
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.
Now, we'll define a result variable, to test for success.
Now, let's initialize our variables!
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.
And now, assuming everything went dandy, we initialize the address info
And now we zero the memory (you could also use memset, but I prefer ZeroMemory-it's faster. )...
And now, assign properties...
Now, we're getting to the exciting stuff!
Let's initialize our 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.
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.
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.
You didn't think we'd forget to check iResult for an error, did you?
Notice that we don't call WSACleanup(), because we have more cleaning up to do.
But otherwise...that must mean the connection succeeded!
Congratz! You've just...oh wait. I still haven't taught you the server yet.
Oh well, use the time in between to study up some more!
/In Function
#ENDREGION
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.
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. )...
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?
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.
Oh well, use the time in between to study up some more!
/In Function
#ENDREGION
Last edited: