- Home /
I need a list of servers using Network Discovery!
Now my question is: As I do to create a list of servers, I have to start several hosts for example. What I want to say is I need to create a List of Servers using the Network Discovery component for a game on LAN
1) Setup your broadcast data. 2) Start Network discovery as a server in host. 3) Start Network discovery as a client in Client. 4) You get List of server in client in OnReceivedBroadcast(string fromAddress, string data) callback. 5) fromAddress is the ipAddress of your server or Host. 6) Data is the broadcast data ,you setup in step 1. 7) Connect using fromAddress to the server by using Networkmanager. 8) Stop server and Client broadcasting of your network discovery after connected.
ok, I understand for the moment I have the code to create a host and join, but I don't understand how I show the list of servers so that users choose which server to join always using Network Discovery,
that by pressing a button I get the list of servers in LAN
Thanks for your answers
In OnReceivedBroadcast(string fromAddress, string data) method, you get the ip addresses of all host who start the server in network broadcast.
so, Instantiate or Bind ip with the specific button and when player click a button, connect using ip address and network manager.
This is my Network Discovery code :
public class DisNetwork : NetworkDiscovery
{
private bool end = false;
public override void OnReceivedBroadcast(string fromAddress, string data)
{
base.OnReceivedBroadcast(fromAddress, data);
Debug.Log("Broadcast recieved from" + fromAddress + " data:" + data);
//Network$$anonymous$$anager.singleton.networkAddress = fromAddress;
// Network$$anonymous$$anager.singleton.StartClient();
end = true;
}
private void LateUpdate()
{
if (end)
{
StopBroadcast();
end = false;
}
}
And this is my Onclickhost code :
int count = 0;
public override void OnStartHost()
{
base.OnStartHost();
discovery.broadcastData = "count: " + count;
discovery.Initialize();
discovery.StartAsServer();
ChangeTo(lobbyPanel);
backDelegate = StopHostClbk;
SetServerInfo("Hosting", networkAddress);
}
void OnCount()
{
count++;
discovery.broadcastData = "count: " + count;
}
Answer by storybelldev · Sep 19, 2018 at 04:55 AM
Here how you can do network discovery
public class CustomNetworkDiscovery : NetworkDiscovery
{
public static CustomNetworkDiscovery Instance;
#region Events
public delegate void ServerDetectedEventHandler(string fromaddress, string data);
public event ServerDetectedEventHandler ServerDetected;
#endregion /Events
#region Event_Invokator
private void OnServerDetected(string address, string data)
{
var handler = ServerDetected;
if (handler != null)
{
handler.Invoke(address, data);
}
}
#endregion /Event_Invokator
#region Unity_Methods
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(gameObject);
}
}
#endregion /Unity_Methods
#region NetworkDiscovery_Methods
public override void OnReceivedBroadcast(string fromAddress, string data)
{
//Don't Call base class intentionally for handle broadcast manualy.
//base.OnReceivedBroadcast(fromAddress, data);
OnServerDetected(fromAddress.Split(':')[3], data);
}
#endregion /NetworkDiscovery_Methods
#region CustomDiscoveryMethodsCallbacks
public bool InitializeNetworkDiscovery()
{
return Initialize();
}
/// <summary>
/// Starts the server broadcasting.
/// Called by a Host only.
/// </summary>
public void StartServerBroadcasting()
{
//Debug.Log("########## StartBroadCasting As Server...");
InitializeNetworkDiscovery();
StartAsServer();
}
/// <summary>
/// Starts the client braodcast.
/// Used to join Game.
/// </summary>
public void StartClientBraodcast()
{
//Debug.Log("########## Listen Broadcast As Client...");
InitializeNetworkDiscovery();
StartAsClient();
}
public void StopBroadcasting()
{
if (running)
{
//Debug.Log("########## Stop Broadcasting...");
StopBroadcast();
}
}
public void SetBroadcastData(string broadcastPayload)
{
broadcastData = broadcastPayload;
}
#endregion /CustomDiscoveryMethodsCallbacks
}
You can't change the broadcast data while broadcast is running. To do so you have to stop broadcast , change the data and start broadcast again.
And This way you can use it
CustomNetworkDiscovery.Instance.ServerDetected += OnServerDetected;
void OnServerDetected(string ip, string data)
{
//Debug.Log("Received broadCast.........");
if (!CheckForIPAvailable(ip))
{
//$$anonymous$$Y UI PREFAB
LobbyServerPrefab serverPrefab = Instantiate(prefab, parent);
serverPrefab.IpAddress = ip;
//Broadcast Data Class(Custom)
NetworkBroadcastData networkBroadcastData = (NetworkBroadcastData)JsonUtility.FromJson(data, typeof(NetworkBroadcastData));
serverPrefab.RoomName = networkBroadcastData.roomName;
serverPrefab.TotalPlayers = networkBroadcastData.totalPlayers;
serverPrefab.ConnectedPlayers = networkBroadcastData.connectedPlayers;
LocalDiscoveryServer server = new LocalDiscoveryServer(ip, serverPrefab, Time.time);
//List of Server Available
if (!localDiscoveryServerList.Contains(server))
{
localDiscoveryServerList.Add(server);
}
else
{
Destroy(serverPrefab.gameObject);
server = null;
}
}
else
{
//If already exist , then update data
UpdateServer(ip, data);
}
}
UI prefab is it self a button ... and we give a server ip to that prefab.
so on button click do...
if (!string.IsNullOrEmpty(IpAddress))
{
networkmanager.networkAddress = _ipAddress;
//Start the client and join it to server
networkmanager.StartClient();
}
youre awesome dude, im trying to set up this but I have some errors ... but I think it's because I do not know where to put exactly each code (I'm talking about the last two codes you sent)
I have several errors and I do not know where to place the codes: /
Answer by Andres41 · Sep 25, 2018 at 04:13 AM
this is my server list code : @storybelldev
public class LobbyServerList : MonoBehaviour { public LobbyManager lobbyManager;
CustomNetworkDiscovery custom;
public RectTransform serverListRect;
public GameObject serverEntryPrefab;
public GameObject noServerFound;
protected int currentPage = 0;
protected int previousPage = 0;
static Color OddServerColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);
static Color EvenServerColor = new Color(.94f, .94f, .94f, 1.0f);
private void Start()
{
FindObjectOfType<CustomNetworkDiscovery>();
}
void OnEnable()
{
currentPage = 0;
previousPage = 0;
foreach (Transform t in serverListRect)
Destroy(t.gameObject);
noServerFound.SetActive(false);
RequestPage(0);
}
public void OnGUIMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matches)
{
if (matches.Count == 0)
{
if (currentPage == 0)
{
noServerFound.SetActive(true);
}
currentPage = previousPage;
return;
}
noServerFound.SetActive(false);
foreach (Transform t in serverListRect)
Destroy(t.gameObject);
for (int i = 0; i < matches.Count; ++i)
{
GameObject o = Instantiate(serverEntryPrefab) as GameObject;
o.GetComponent<LobbyServerEntry>().Populate(matches[i], lobbyManager, (i % 2 == 0) ? OddServerColor : EvenServerColor);
o.transform.SetParent(serverListRect, false);
}
}
public void ChangePage(int dir)
{
int newPage = Mathf.Max(0, currentPage + dir);
//if we have no server currently displayed, need we need to refresh page0 first instead of trying to fetch any other page
if (noServerFound.activeSelf)
newPage = 0;
RequestPage(newPage);
}
public void RequestPage(int page)
{
previousPage = currentPage;
currentPage = page;
lobbyManager.matchMaker.ListMatches(page, 6, "", true, 0, 0, OnGUIMatchList);
}
// CustomNetworkDiscovery.Instance.ServerDetected += OnServerDetected;
void OnServerDetected(string ip, string data) { Debug.Log("Received broadCast........."); if (!CheckForIPAvailable(ip)) {
//MY UI PREFAB
LobbyServerPrefab serverPrefab = Instantiate(serverEntryPrefab);
serverPrefab.IpAddress = ip;
//Broadcast Data Class(Custom)
NetworkBroadcastData networkBroadcastData = (NetworkBroadcastData)JsonUtility.FromJson(data, typeof(NetworkBroadcastData));
serverPrefab.RoomName = networkBroadcastData.roomName;
serverPrefab.TotalPlayers = networkBroadcastData.totalPlayers;
serverPrefab.ConnectedPlayers = networkBroadcastData.connectedPlayers;
LobbyServerList server = new LobbyServerList(ip, serverPrefab, Time.time);
//List of Server Available
if (!LobbyServerList.Contains(server))
{
LobbyServerList.Add(server);
}
else
{
Destroy(serverPrefab.gameObject);
server = null;
}
}
else
{
//If already exist , then update data
UpdateServer(ip, data);
}
}
}
this my Prefab or lobby server entry:
using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; using UnityEngine.Networking.$$anonymous$$atch; using UnityEngine.Networking.Types; using System.Collections;
namespace Prototype.NetworkLobby { public class LobbyServerEntry : $$anonymous$$onoBehaviour {
CustomNetworkDiscovery custom;
public Text serverInfoText;
public Text slotInfo;
public Button joinButton;
public void Start()
{
FindObjectOfType<CustomNetworkDiscovery>();
}
public void Populate($$anonymous$$atchInfoSnapshot match, Lobby$$anonymous$$anager lobby$$anonymous$$anager, Color c)
{
serverInfoText.text = match.name;
slotInfo.text = match.currentSize.ToString() + "/" + match.maxSize.ToString(); ;
NetworkID networkID = match.networkId;
joinButton.onClick.RemoveAllListeners();
joinButton.onClick.AddListener(() => { Join$$anonymous$$atch(networkID, lobby$$anonymous$$anager); });
GetComponent<Image>().color = c;
}
public void Join$$anonymous$$atch(NetworkID networkID, Lobby$$anonymous$$anager lobby$$anonymous$$anager)
{
lobby$$anonymous$$anager.match$$anonymous$$aker.Join$$anonymous$$atch(networkID, "", "", "", 0, 0, lobby$$anonymous$$anager.On$$anonymous$$atchJoined);
lobby$$anonymous$$anager.backDelegate = lobby$$anonymous$$anager.StopClientClbk;
lobby$$anonymous$$anager._is$$anonymous$$atchmaking = true;
lobby$$anonymous$$anager.DisplayIsConnecting();
}
}
}
And my list of players:
//List of players in the lobby public class LobbyPlayerList : $$anonymous$$onoBehaviour { public static LobbyPlayerList _instance = null;
public RectTransform playerListContentTransform;
public GameObject warningDirectPlayServer;
public Transform addButtonRow;
protected VerticalLayoutGroup _layout;
protected List<LobbyPlayer> _players = new List<LobbyPlayer>();
public void OnEnable()
{
_instance = this;
_layout = playerListContentTransform.GetComponent<VerticalLayoutGroup>();
}
public void DisplayDirectServerWarning(bool enabled)
{
if(warningDirectPlayServer != null)
warningDirectPlayServer.SetActive(enabled);
}
void Update()
{
//this dirty the layout to force it to recompute evryframe (a sync problem between client/server
//sometime to child being assigned before layout was enabled/init, leading to broken layouting)
if(_layout)
_layout.childAlignment = Time.frameCount%2 == 0 ? TextAnchor.UpperCenter : TextAnchor.UpperLeft;
}
public void AddPlayer(LobbyPlayer player)
{
if (_players.Contains(player))
return;
_players.Add(player);
player.transform.SetParent(playerListContentTransform, false);
addButtonRow.transform.SetAsLastSibling();
PlayerList$$anonymous$$odified();
}
public void RemovePlayer(LobbyPlayer player)
{
_players.Remove(player);
PlayerList$$anonymous$$odified();
}
public void PlayerList$$anonymous$$odified()
{
int i = 0;
foreach (LobbyPlayer p in _players)
{
p.OnPlayerListChanged(i);
++i;
}
}
}
Your answer
Follow this Question
Related Questions
Unity networking tutorial? 6 Answers
Storing instances of a script in a list. 0 Answers
A node in a childnode? 1 Answer
Master Server Current Games List 1 Answer
Master Server Problems (networking) 1 Answer