How To Start P2P (Peer-to-Peer) Using MatchMaker

MatchMaker offers a utility function to help you start P2P communication with matched users.

MatchMaker and TeamMatchMaker class have a method to exchange client addresses to start P2P communication.

The example below uses MatchMaker class.

// This list keeps track of all P2P class instances
List<P2P> peers = new List<P2P>();

// This event callback receives all matched clients' addresses
matchmaker.OnP2PAddressSync += (Diarkis.Lib.Packet.P2PClientAddr[] clients) =>
  for (int i = 0; i < clients.Length; i++)
    Diarkis.Lib.Packet.P2PClientAddr addr = clients[i];

    // diarkisUDPClient is the Diarkis UDP client instance
    // that is connected to the server
    Diarkis.Modules.P2P peerClient = new Diarkis.Modules.P2P(diarkisUDPClient);

    peerClient.OnReady += OnP2PReady;

    peerClient.OnFail += OnP2PFail;

    peerClient.OnMessage += OnMessage;

    peerClient.Connect(addr.PublicAddr, addr.LocalAddr);

    // peers is used in Update method

private void OnP2PReady(string peerAddress, int peerPort, double holePunchTimeInMilliseconds)
  // P2P is now ready!

private void OnP2PFail(string peerAddress, int peerPort)
  // P2P has failed...

private void OnMessage(string senderAddress, int senderPort, byte[] msg)
  // Handle the message sent from another client

// For Unity Game Engine...
void Update()
  // We must call Update of each P2P class instances
    for (int i = 0; i < peers.Count; i++)

// Calling this triggers OnP2PAddressSync event on all matched user clients

Last updated