MatchMaker を使って P2P (Peer-to-Peer) 通信をする

MatchMaker では、P2P 通信を開始するための実装をより簡略化するための機能を提供しています。

MatchMaker と TeaMatchMaker のクラスではそれぞれ、P2P 通信を開始するためのメソッドを用意しています。

以下の例では、MatchMaker クラスを使っています。

// 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
peers.Add(peerClient);
}
};

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
lock(peers)
{
for (int i = 0; i < peers.Count; i++)
{
peers[i].Update();
}
}
}

// Calling this triggers OnP2PAddressSync event on all matched user clients
matchmaker.P2PAddressSync();