Introduction
Over the years, there's always this problem that I face whenever I need to share data between systems or machines over the network - the freely available networking libraries and code snippets are either sometimes broken or I need to read up a lot before I can make sense out of them. So I've decided to write a simple and flexible networking class for everyone to use.
Cool Features
Since it's simple and meant to get you started in minutes, you won't be seeing a long list of features. But do take note of its ease-of-use and convenience in terms of the data handling and setup.
- Just one object for networking (either client or server)
- Easy selection of UDP or TCP mode
- No need for explicit data serialization before sending/retrieval; takes any data structure
Using the Code
It's easy to see how XNet
can be integrated into any application in minutes. The only thing you have to do other than choosing where you want to create the XNet
object and placing the sending/receiving functions is to define your own structure for the data you want to transmit before compilation. This can be done in MyDataStruct.h. XNet
automatically handles the serialization for you by pointer "casting" and then reverses it at the receiving end. Check out the source codes for the XNet
class for more information.
#include "XNet.h"
int main(void)
{
MyDataStruct ds, dr;
ds.data[0]=10.f;
ds.data[1]=20.f;
ds.data[2]=30.f;
ds.data[3]=40.f;
ds.data[4]=50.f;
ds.data[5]=60.f;
XNet* xnet = XNet::Instance();
#ifdef TCP_SERVER
xnet->init( SERVER, 2006, TCP );
dr = xnet->receiveData();
std::cout << "Random integrity check: " << dr.data[2] << std::endl;
xnet->sendData( ds );
std::cout << "Sent!" << std::endl;
#endif
#ifdef TCP_CLIENT
xnet->init( CLIENT, 2006, TCP, "localhost" );
xnet->sendData( ds );
std::cout << "Sent!" << std::endl;
dr = xnet->receiveData();
std::cout << "Random integrity check: " << dr.data[5] << std::endl;
#endif
#ifdef UDP_SERVER
xnet->init( SERVER, 2006, UDP );
dr = xnet->receiveData();
std::cout << "Random integrity check: " << dr.data[2] << std::endl;
xnet->sendData( ds );
std::cout << "Sent!" << std::endl;
#endif
#ifdef UDP_CLIENT
xnet->init( CLIENT, 2006, UDP, "localhost" );
xnet->sendData( ds );
std::cout << "Sent!" << std::endl;
dr = xnet->receiveData();
std::cout << "Random integrity check: " << dr.data[5] << std::endl;
#endif
getchar(); delete xnet;
return 0;
}
Points of Interest
I have even built XNet
as Matlab Simulink blocks due to the need in a piece of research work. XNet
provides an easy mode of communication between Matlab and an external C++ console-based application without the hassle of network setup as in the case of using other networking blocks or libraries. For those who are interested, you can contact me for the Simulink blocks.
History
- 12th February, 2006: Initial post