Diarkis P2P - How To Exchange Client Addresses Between Clients

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

  1. Join a room
  2. Exchange client addresses using Diarkis Room's BroadcastTo and/or MessageTo
  3. 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.

If you are using Unity Game Engine, you may call Update in Unity's Update.

The example code below shows how to start peer-to-peer using Diarkis P2P:

// Pass Diarkis UDP client class instance
Diarkis.Modules.P2P p2p = new Diarkis.Modules.P2P(diarkisUdpClient);

// Set up event listener callbacks

// This event is raised when peer-to-peer connection is successful
p2p.OnReady += (string peerAddress, int peerPort, double, holePunchTimeInMilliseconds) =>
{

}

// This event is raised when peer-to-peer connection fails
p2p.OnFail += (string peerAddress, int peerPort) =>
{

}

// This event is raised when a peer sends a message
p2p.OnMessage += (string peerAddress, int peerPort, byte[] message) =>
{

}

// This event is raised when socket related excetion is caught
p2p.OnException += (int errCode, string errMessage) =>
{

}

// 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);