Peer to Peer connections
Note
This is part of the Low Level Transport for advanced users only.
Establishing a P2P connection is as simple as calling Host.Connect()
on both hosts. Even if both hosts have their ports blocked, the connection will still be established.
Connect method requires a valid IPEndPoint which consists of the remote IP address and port they're listening on. A common way of exchanging the address is to connect to a third party relay (which doesn't have ports blocked), and either notifying the peer you're trying to connect via the relay, or simply tell the relay that you're ready to accept connections and keeping the connection to the relay open.
Hosting a P2P server
The most common situation where you need P2P connections is when you want to create a server but don't want ports to be forwarded. For example, if you want to allow players to create P2P servers in game and let other players connect to them.
This is the entire process:
- Server connects to Relay and keeps the connection open
- Client connects to Relay and asks it for a list of servers
- Client chooses a server and notifies Relay that they're about to connect to it
- Relay notifies Server about the new connection attempt
- Server initiates connection to the Client
- Client initiates connection to the Server
- P2P connection between Server and Client is established
The relay in the above process must not have blocked ports so both servers and clients can connect to it. Right now we do not offer relay hosting, but there a plans for it in the future. If you're using Steam, you can avoid needing a relay altogether by using Steam to notify players when they need to initiate connections. This would enable to to avoid all hosting costs. If you have questions on how to achieve this, message us on discord, we're always happy to help and provide examples.
How it works
Most people are connected to the internet via their router. You can connect multiple machines to the router, and all machines have the same public IP. This creates an issue where your router does not know which machine to forward incoming packets to. The way routers solve this problem is by remembering outgoing packets. If you send an outgoing packet to a specific IP and port, router remembers that for a short duration (a couple of minutes), and any packets that it receives from that IP and port it forwards to you. This means if both peers start sending eachother packets at the same time, eventually the packets are going to start getting through.
This process is called UDP hole punching. You can read more about it here.