Utility class to build blocks of data to transfer over the network.
Append data to the end of a packet
Test the validity of a packet, for reading
Clear a packet
Create a new packet by copying an existing one
Create a new packet
Destroy a packet
Tell if the reading position has reached the end of a packet
Get a pointer to the data contained in a packet
Get the size of the data contained in a packet
Functions to extract data from a packet
Functions to insert data into a packet
1 int x = 24; 2 string s = "hello"; 3 double d = 5.89; 4 5 // Group the variables to send into a packet 6 auto packet = new Packet(); 7 packet.write(x); 8 packet.write(s); 9 packet.write(d); 10 11 // Send it over the network (socket is a valid TcpSocket) 12 socket.send(packet); 13 14 //////////////////////////////////////////////////////////////// 15 16 // Receive the packet at the other end 17 auto packet = new Packet(); 18 socket.receive(packet); 19 20 // Extract the variables contained in the packet 21 int x; 22 s; 23 double d; 24 if (packet.read(x) && packet.read(s) && packet.read(d)) 25 { 26 // Data extracted successfully... 27 }
$(PARA Packets also provide an extra feature that allows to apply custom transformations to the data before it is sent, and after it is received. This is typically used to handle automatic compression or encryption of the data. This is achieved by inheriting from sf::Packet, and overriding the onSend and onReceive functions.)
1 class ZipPacket : Packet 2 { 3 override const(void)[] onSend() 4 { 5 const(void)[] srcData = getData(); 6 7 return MySuperZipFunction(srcData); 8 } 9 10 override void onReceive(const(void)[] data) 11 { 12 const(void)[] dstData = MySuperUnzipFunction(data); 13 14 append(dstData); 15 } 16 } 17 18 // Use like regular packets: 19 auto packet = new ZipPacket(); 20 packet.write(x); 21 packet.write(s); 22 packet.write(d);
$(TCPSOCKET_LINK), $(UDPSOCKET_LINK)
Packets provide a safe and easy way to serialize data, in order to send it over the network using sockets (sf::TcpSocket, sf::UdpSocket).
Packets solve 2 fundamental problems that arise when transferring data over the network:
$(PARA The $(U Packet) class provides both input and output modes.)