PolyPeer.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * PolyPeer.h
  3. * Poly
  4. *
  5. * Created by Ivan Safrin on 3/6/09.
  6. * Copyright 2009 __MyCompanyName__. All rights reserved.
  7. *
  8. */
  9. // @package Network
  10. #pragma once
  11. #include "PolyGlobals.h"
  12. #include "PolyCoreServices.h"
  13. #include "PolyThreaded.h"
  14. #include "PolySocket.h"
  15. #include <vector>
  16. using std::vector;
  17. namespace Polycode {
  18. typedef struct {
  19. unsigned int headerHash;
  20. unsigned int sequence;
  21. unsigned int ack;
  22. unsigned short reliableID;
  23. unsigned int ackBitfield;
  24. unsigned short size;
  25. unsigned short type;
  26. } PacketHeader;
  27. typedef struct {
  28. PacketHeader header;
  29. char data[MAX_PACKET_SIZE];
  30. } Packet;
  31. typedef struct {
  32. Packet *packet;
  33. unsigned int timestamp;
  34. } SentPacketEntry;
  35. class _PolyExport PeerConnection {
  36. public:
  37. PeerConnection() { localSequence = 0; remoteSequence = 0; reliableID = 1;}
  38. ~PeerConnection(){}
  39. void ackPackets(unsigned int ack);
  40. unsigned int localSequence;
  41. unsigned int remoteSequence;
  42. unsigned int reliableID;
  43. vector<SentPacketEntry> reliablePacketQueue;
  44. vector<unsigned short> recentReliableIDs;
  45. Address address;
  46. };
  47. class _PolyExport Peer : public Threaded, public EventDispatcher {
  48. public:
  49. Peer(unsigned int port);
  50. ~Peer();
  51. void handleEvent(Event *event);
  52. virtual void handlePacket(Packet *packet, PeerConnection *connection){};
  53. virtual void handlePeerConnection(PeerConnection *connection){};
  54. Packet *createPacket(const Address &target, char *data, unsigned int size, unsigned short type);
  55. void sendData(const Address &target, char *data, unsigned int size, unsigned short type);
  56. void sendReliableData(const Address &target, char *data, unsigned int size, unsigned short type);
  57. void sendReliableDataToAll(char *data, unsigned int size, unsigned short type);
  58. void sendDataToAll(char *data, unsigned int size, unsigned short type);
  59. void sendPacket(const Address &target, Packet *packet);
  60. bool checkPacketAcks(PeerConnection *connection, Packet *packet);
  61. PeerConnection *getPeerConnection(const Address &address);
  62. PeerConnection *addPeerConnection(const Address &address);
  63. virtual void updatePeer(){}
  64. void updateThread();
  65. protected:
  66. Timer *updateTimer;
  67. vector<PeerConnection*> peerConnections;
  68. Socket *socket;
  69. };
  70. }