Send Strings across BitStream and RakNet

RakNet is a C++ networking engine to help you write multiplayer games. BitStream is a method for converting data such as variables into bytes to send out across the network.

In many cases you would send data with BitStream from one client to the server (or another client) like this:

bs.Write((char*)&m_position, sizeof(glm::vec3));

and receive it like this:

bsIn.Read((char*)&m_position, sizeof(glm::vec3));

Effectively when you send variables across BitStream like above, the & symbol tells the BitStream that you are sending a memory address (the literal location of where the data is stored in your PC’s memory) and pointing to the first byte in that address, with sizeof specifying how many bytes make up the data. This ensures it sends and receives the whole piece of data. Unfortunately, you can’t send standard Strings in this way, so RakNet gave us their method, the RakString. It’s an alternative variable to std::String that you can send across BitStream and later convert back to std::String. It’s also 3x faster than std::String apparently. If you’ve already included the RakPeerInterface.h and BitStream.h, then you should create a new member variable in the header of your class for a RakString.

RakNet::RakString m_spritePath; // file path of the sprite

You can then simply send it like this:

bs.Write(m_spritePath);

You don’t need to cast it to a char* because RakString is native to RakNet. You can receive it the same way:

bsIn.Read(m_spritePath);

Then, before you use it, it is a good idea to convert it back to a normal string.

std::string temp = m_spritePath;

That’s all there is to it. You can take a further look at BitStreams here on their official site and learn more about sending strings here. For a more indepth look at the class overview click here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s