In order to start peer-to-peer communication, clients must exchange their client address.
We use Diarkis Room to exchange client addresses to start peer-to-peer communication using Diarkis P2P.
NOTE: Diarkis P2P supports UDP network protocol only.
Steps
- Join a room
- Exchange client addresses using Diarkis Room's BroadcastTo and/or MessageTo
- Start peer-to-peer communication using Diarkis P2P
1. Join A Room
To exchange client addresses, you must first create and/or join a room.
To learn how to create a room, please read creating a room and receiving room creation response.
To learn how to join a room, please read joining a room, and receiving room join response and detecting a new member joined.
2. Exchanging Client Address
We use BroadcastTo in this example.
The code below shows how to retrieve your own client address:
string clientAddress = diarkisUdpClient->GetAddress();
To learn more about sending a client address to other players in the room, please read sending a message and receiving a message.
3. Start Peer-to-Peer Communication With Diarkis P2P
With the client addresses from other players in the room, we are ready to start peer-to-peer communications.
Update
In order for Diarkis P2P to work properly, you must call Update method of Diarkis P2P in a separate thread loop. Update controls all events of Diarkis P2P.
The example code below shows how to start peer-to-peer using Diarkis P2P:
// Set up P2P class instance with Diarkis UPD client instance
p2pClientA = shared_ptr<IDiarkisP2P>(DiarkisCreateP2P(diarkisUdpClient));
// Set up Event listeners
// This event is raised when peer-to-peer connection is successful and ready to send and receive messages
REG_EVENT(p2pClientA->GetReadyEvent(), [this](void*, const DiarkisReadyEventArgs& args) { /* do something magical here */ });
// This event is raised when peer-to-peer connection failed
REG_EVENT(p2pClientA->GetFailEvent(), [this](void*, const DiarkisFailEventArgs& args) { /* do something magical here */ });
// This event is raised when you receive a message from the peer
REG_EVENT(p2pClientA->GetMessageEvent(), [this](void*, const DiarkisMessageEventArgs& args) { /* do something magical here */ });
// This event is raised when socket related exception is caught
REG_EVENT(p2pClientA->GetExceptionEvent(), [this](void*, const DiarkisExceptionEventArgs& args) { /* do something magical here */ });
// Pass a client address
// The format of client address is 0.0.0.0:0 as a string
// where 0.0.0.0 would be the address and 0 after : is the port
// We need to separate the address from the port
p2p->Connect(address, port);