Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Andres41 · Sep 17, 2018 at 03:51 AM · networkinglistserver

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

Comment
Add comment · Show 13
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image storybelldev · Sep 17, 2018 at 04:48 AM 0
Share

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.

avatar image Andres41 storybelldev · Sep 17, 2018 at 05:49 AM 0
Share

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

avatar image storybelldev Andres41 · Sep 17, 2018 at 01:17 PM 0
Share

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.

Show more comments
avatar image Andres41 · Sep 19, 2018 at 03:10 AM 0
Share

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;
             }
         }
avatar image Andres41 Andres41 · Sep 19, 2018 at 03:11 AM 0
Share

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;
     }

2 Replies

· Add your reply
  • Sort: 
avatar image
2

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
 }
Comment
Add comment · Show 10 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image storybelldev · Sep 19, 2018 at 04:56 AM 0
Share

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.

avatar image storybelldev · Sep 19, 2018 at 05:01 AM 0
Share

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);
             }
         }
avatar image storybelldev storybelldev · Sep 19, 2018 at 05:09 AM 0
Share

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();
             }
avatar image Andres41 storybelldev · Sep 20, 2018 at 01:20 AM 0
Share

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)

avatar image Andres41 Andres41 · Sep 20, 2018 at 04:14 AM 0
Share

I have several errors and I do not know where to place the codes: /

Show more comments
avatar image
0

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);
         }
     }



 }
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Andres41 · Sep 25, 2018 at 04:14 AM 0
Share

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();
     }



 }

}

avatar image Andres41 Andres41 · Sep 25, 2018 at 04:15 AM 0
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

130 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges