Advertisement

ENet packet question

Started by October 31, 2014 01:15 PM
5 comments, last by coquinounet 10 years ago

Hello,

I'm making a little game server with ENet and I've tried to use it using packet that I made (with an header and data in body) but when I do it and I send a packet, it appears that it's never the same data which are received although I send the same packet.

If you have a tutorial or examples to show me, it would be nice.

Thanks

I can find plenty of tutorials by searching for "ENet tutorial". Can you show us the code that isn't working?

Advertisement

Well for example i have this packet struct


class HeaderPacket
{
	protected:
		std::vector<char> data;
	public:
		const std::vector<char> getData() { return data; }
		HeaderPacket(char cmd = 0, unsigned int id = 0)
		{
			data.insert(data.end(), cmd, sizeof(cmd));
			data.insert(data.end(), id, sizeof(id));
		}
};

A simple enum with the packets types


enum PacketType : char
{
	PACKET_Handshake = 0x01,
	PACKET_Hello = 0x02
};

And when my client connect, I do that :


HeaderPacket *thepacket = new HeaderPacket(PACKET_Handshake, 5);

ENetPacket *packet = enet_packet_create(&thepacket->getData(), thepacket->getData().size(), ENET_PACKET_FLAG_RELIABLE);

enet_peer_send(event.peer, 0, packet);

There is probably beginner errors, sorry


data.insert(data.end(), id, sizeof(id));

This line does not insert 4 chars containing the relevant bytes from 'id'. Instead it inserts 'id' chars which all contain the same value 4 - i.e. sizeof(id).

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Well i don't get it, what should i do ?

Read the documentation for the std::vector<>::insert() function.

http://www.cplusplus.com/reference/vector/vector/insert/

Currently, you're using the "fill" variant.
You want to be using the "range" variant. Which means passing two char pointers, not a pointer and a length.
For example:

myVector.insert(myVector.end(), (char *)&id, (char *)&id + sizeof(id));
enum Bool { True, False, FileNotFound };
Advertisement

Thanks ! That works

Just in case for those who want do the same thing, to send the packet you must do that


HeaderPacket thepacket = HeaderPacket(PACKET_Handshake, 5);

ENetPacket *packet = enet_packet_create((const char*)&thepacket.getData()[0], thepacket.getData().size(), ENET_PACKET_FLAG_RELIABLE);

enet_peer_send(event.peer, 0, packet);

This topic is closed to new replies.

Advertisement