XSocket For Windows
by Karsten Pedersen
xsocket-0.8.3-win32-src.zip
About
This is a simple Object Orientated Winsock2 wrapper for windows which was created to allow easy netcode for our game to be entered in Microsoft Imagine Cup 2008.
How to use
I have included a sample usage app along with the XSocket.h/.cpp files for people who learn better by example.
For those who were looking for a step by step walkthrough... I hope this will suffice.
First make sure to...
Also make sure all this is done within a class called Logic as we will be passing the class instance to the XSocket class
Server
Create a new instance of XSocket which will do all the listening...
XSocket* listenSocket = new XSocket(this, 9999);
Notice the "this"? This allows the XSoket class to be able to call methods from the parent class (Logic). The 9999 is the port(int).
Now simply call...
This will not block your code because it simply creates a thread which keeps accepting connections and calling the connectionRecieved() method. When this gets called we need another socket to actually accept the connection. To do this I usually create an array of XSockets...
XSocket* xSockets[256];
int xSocketsCount = 0;
You might like to keep count of what the last socket is so you can keep adding to it. Now in the connectionRequest() method simply put...
xSockets[xSocketsCount] = new XSocket(this);
xSockets[xSocketsCount]->xAccept(listenSocket);
This will create a new instance of the current XSocket and also connect it to the requesting client. If the accept is successful, the method Logic::connect() will be called.
When they disconnect, the message disconnect() will be called so you might like to reuse the XSocket.
When data is recieved by the XSocket the method Logic::dataRecieved(string data) will be called. data contains the message that was sent.
You can send a message to the client with xSockets[xSocketsCount]->xSend("hello"). To send it to all clients put it in a simple loop like...
for(int index = 0; index < xSocketsCount; index++)
{
xSockets[index]->xSend("hello");
}
Client
Do same as server for most things apart from...
XSocket* xSocket = new XSocket(this, host, port);
xSocket->connect();
Then the same xSend(), dataRecieved(), connected(), disconnected() methods apply.
Things to remember
All the methods like connectionRequest() need to be made even if you are working on the client. (just leave it blank)
The class which contains the XSocket class must be called Logic
#include "XSocket.h" MUST be included before windows.h or any header which included windows.h (incuding darkgdk.h). This is because windows.h includes the old winsock.h which conflicts with winsock2.h which my wrapper uses
Extra
I know this brief tutorial is almost useless, so please feel free to post any questions
Also if you would like a version to work on Linux/BSD let me know. It is also slightly more up to date.
regards,