I am trying to Network a small 2 player Unity game. This is my first go at networking, so please feel free to correct me on anything I am doing wrong. I am attempting to make a simple matchmaking service where, on the main menu of the game, a player can click the Find Match button. This will execute the following function
private HostData[] hostList;
private const string typeName = "UniqueGameName";
private const string gameName = "RoomName";
public void FindMatch() {
RefreshHostList();
if (hostList != null) {
JoinServer(hostList[0]);
} else {
StartServer();
}
}
And here are the corresponding methods called in that function.
private void RefreshHostList()
{
MasterServer.RequestHostList(typeName);
}
void OnMasterServerEvent(MasterServerEvent msEvent)
{
if (msEvent == MasterServerEvent.HostListReceived)
hostList = MasterServer.PollHostList();
}
private void JoinServer(HostData hostData)
{
Network.Connect(hostData);
}
private void StartServer()
{
Network.InitializeServer(2, 25000, !Network.HavePublicAddress());
MasterServer.RegisterHost(typeName, gameName);
}
The idea is, when the player clicks Find Match, it will refresh the host list. If it finds a host, it will join their server and begin a match. If it doesn't, it will begin its own server and wait for another player. When testing this, the first player that clicks Find Match is able to start a server, but then the second player receives the error message "...Is the listen port already in use?". When I debug and step through my program, the second player's hostList is always null, even with the first players successful server creation and registration.
Are you using both instances of app on same machine? If you occupy network port once then you are not able to initialize server on same port on the same machine.
In general I would recommend looking into SingalR technology for your needs, it uses websockets.