Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
SFML Game Development.pdf
Скачиваний:
209
Добавлен:
28.03.2016
Размер:
4.19 Mб
Скачать

Chapter 10

Data transport

We already know some things about how sockets behave and their inner workings, but we only talked about sending and receiving data in an abstract way. We referred to the data as arrays of bytes, which we simply send and receive, but how is it done?

Indeed, what is passed on through the network is merely a block of data, a collection of raw bytes. Therefore, it must be sent in a way that can be read again by the remote machine. Your data could be anything, text, numbers, images, sound, or pretty much anything that is digital.

For this, we pack and unpack our data into a byte array when sending/receiving it! When we use the term packet, we refer to a collection of bytes, which contain one or more primitives (integers, floats, and others). This is very efficient from the perspective that we don't have additional overhead for sending multiple primitives;

they all go at once in the same byte array. However, we have a per-packet overhead, namely the packet headers that are required by the lower-level protocols (most notably IP and TCP/UDP).

Packing and unpacking is not a complicated thing to do, but can be troublesome to get right when done from scratch.

To add complexity to this task, you can't make assumptions on what byte ordering system the target machine is using. There are big-endian and little-endian operating systems, which mean a different ordering of bytes in memory. You can look at it as reversing the order of the bits of a variable. Therefore, for example, the number 3 in a little-endian system, when transferred to a big-endian one is not the number 3 anymore, as the bits were reversed. This needs to be taken into account.

Luckily, SFML has also solved this! You can and should use the sf::Packet class to address this issue. It is very simple to work with and it will make your life easier in every way, as opposed to implementing it all from scratch. If properly understanding the socket functionality is half of the work, understanding packets would be the other half into making a good networked application.

The following code shows how to pack some data and send it:

sf::Packet packet;

std::string myString = "Hello Sir!"; sf::Int32 myNumber = 20;

sf::Int8 myNumber2 = 3;

packet << myString << myNumber << myNumber2; mySocket.send(packet);

[ 241 ]

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]