Unity-Technologies / multiplayer-community-contributions

Community contributions to Unity Multiplayer Networking products and services.
MIT License
429 stars 161 forks source link

What is the correct way to establish a connection for a custom transport #125

Closed yuchenz27 closed 2 years ago

yuchenz27 commented 2 years ago

I am implementing a custom transport using iOS MultipeerConnectivity. I had a working version of old MLAPI, but now I am upgrading it to fit the new Netcode. I tried several ways to establish the connection and some of them worked, but I am sure what is the best way to do it and the logic behind it. I will explain how I am doing it currently:

Say we have two devices A and B, A is the host and B is a client, when they gets connected through MultipeerConnectivity

  1. On client B, return NetworkEvent.Connect in function PollEvent:

    public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment<byte> payload, out float receiveTime)
    {
    if (m_NewPeerDidConnect)
    {
        m_NewPeerDidConnect = false;
        // The transportId of the host.
        clientId = m_NewPeerClientId;
        payload = new ArraySegment<byte>();
        receiveTime = Time.realtimeSinceStartup;
        return NetworkEvent.Connect;
    }
    }

    By doing above, Netcode will immediately send a connection request message to host A.

  2. When host A receives the connection request message, first return NetworkEvent.Connect in function PollEvent with client B's transportId and empty data payload, then for the same function, return NetworkEvent.Data with client B's transportId and the data payload sent along with the connection request message. By doing so, Netcode will send another message back to client B.

  3. When client B receives the message sent by the host at the end of step 2, the callback function NetworkManager.Singleton.OnClientConnectedCallback is called and it automatically sends another message to host A.

  4. When host A receives the message sent by the client at the end of step 3, it calls the same callback function NetworkManager.Singleton.OnClientConnectedCallback, and the bidirectional connection is finally established.

Is this the correct way to establish a connection? Is there a better way to do this?

I am currently encountering with this problem https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/1431, I think probably a more proper way to establish the connection might solve it.

Thank you for finish reading this!

yuchenz27 commented 2 years ago

Ok I have figured the problem out, the reason was that I caused a overflow problem at transport layer.