Search Unity

NetworkDiscovery sample

Discussion in 'Multiplayer' started by seanr, Sep 14, 2015.

  1. seanr

    seanr

    Unity Technologies

    Joined:
    Sep 22, 2014
    Posts:
    669
    Attached is a simple project that uses the NetworkDiscovery component that is new in Unity 5.2.

     

    Attached Files:

    CrandellWS, JuanFLZ and MrLucid72 like this.
  2. Muckel

    Muckel

    Joined:
    Mar 26, 2009
    Posts:
    471
    Thank you very much!
    Never mind it's so simple now :)
    M.
     
    Last edited: Sep 14, 2015
  3. HugoZandel

    HugoZandel

    Joined:
    Mar 11, 2014
    Posts:
    52
    Just to help out new comers. If you don't want to use the default gui, you'll have to override OnReceivedBroadcast() and parse the data string. You then can join a game directly or add the game to a server browser.

    @seanr Is it always
    Code (CSharp):
    1. NetworkManager:adr:port
    ?
     
    Honorsoft likes this.
  4. yaumulisnain

    yaumulisnain

    Joined:
    Oct 26, 2015
    Posts:
    4
    Thank you very much!

    @seanr can you tell me how to use network discovery with custom UI

    Thanks :)
     
  5. seanr

    seanr

    Unity Technologies

    Joined:
    Sep 22, 2014
    Posts:
    669
    Yes, it is that when using NetworkDiscovery with the NetworkManager.
     
  6. neegoool

    neegoool

    Joined:
    Apr 22, 2013
    Posts:
    1
    Will there be any support for multiple clients?
     
  7. bitbutter

    bitbutter

    Joined:
    Jul 19, 2012
    Posts:
    60
    I'd like to have my android phone act as a client and my desktop machine act as server but I've been unable to get this example working for this scenario.

    If I run this example on my desktop (Initilalise Broadcast > Start Broadcasting) and laptop (Initialize Broadcast > Listen for Broadcast) the laptop successfully reports the desktop IP.

    But if i export the scene and run it on my android phone (Initialize Broadcast > Listen for Broadcast) it fails to find the server (doesn't report game IP).

    All machines are connected to the same wifi network.

    Does anyone have an idea of what I may be doing wrong or what I need to look at to get the android client to see the server? (I can provide additional information about my setup if necessary of course)
     
  8. faneric

    faneric

    Joined:
    May 15, 2013
    Posts:
    10
  9. sita

    sita

    Joined:
    Jul 30, 2015
    Posts:
    9
    Hi seanr (@seanr )

    When I initialize the broadcast as server, the other device(client) is connected to the server (connectivity successful) IP. But the packets are not being sent from the game port.
    I keep getting this error message : " UNet Client Disconnect Error: Timeout UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate() site:forum.unity3d.com".
    But works completely fine when I run the server and client on the same system.

     
    Last edited: Dec 9, 2015
  10. Qwertyuiop1234

    Qwertyuiop1234

    Joined:
    Jul 21, 2015
    Posts:
    10
    @seanr
    Hi. Tested this sample in editor (5.2.3f1). On 3rd host restart (Lan host, stop, lan host, stop, lan host) I get several errors:

    Broadcast discovery has been already running. Stop discovery first before repeat this call
    UnityEngine.Networking.NetworkDiscovery:StartAsServer()
    MyNetManager:OnStartHost() (at Assets/MyNetManager.cs:13)
    UnityEngine.Networking.NetworkManagerHUD:OnGUI()

    NetworkDiscovery StartBroadcast failed err: 8
    UnityEngine.Networking.NetworkDiscovery:StartAsServer()
    MyNetManager:OnStartHost() (at Assets/MyNetManager.cs:13)
    UnityEngine.Networking.NetworkManagerHUD:OnGUI()

    Cannot open socket on ip {*} and port {7777}; check please your network, most probably port has been already occupied
    UnityEngine.Networking.NetworkManagerHUD:OnGUI()

    StartServer listen failed.
    UnityEngine.Networking.NetworkManagerHUD:OnGUI()
     
  11. Who-am-I

    Who-am-I

    Joined:
    Mar 29, 2014
    Posts:
    73
    Hi @seanr
    Sorry for my bad English,
    I am trying to run your example of Network Discovery. If I run server and client both on my PC its working fine. If I run server on other PC within same network and I run client on different PC. Its is finding server(IP) after click on 'Listen for Broadcast' but after click on IP button, my Player does not create clone. I am working with Unity 5.3.
     
  12. papiot

    papiot

    Joined:
    Jan 27, 2015
    Posts:
    10
    Hey - did you manage to get this resolved? I am trying to do exactly the same thing - have the PC as server and android phone as client
     
  13. eshan-mathur

    eshan-mathur

    Joined:
    Nov 22, 2011
    Posts:
    118
    Can this class be used to have two phones discover each other without knowing which one will be server/client? The only way to know that is to have the user select an option, but we'd like a more seamless, no-interaction type experience for our casual audience.

    I've posted more detail about my question in the link below, but I thought I'd mention it here since it's very related to the capabilities of NetworkDiscovery.

    http://forum.unity3d.com/threads/co...action-over-local-wifi-is-it-possible.375724/
     
  14. Who-am-I

    Who-am-I

    Joined:
    Mar 29, 2014
    Posts:
    73
    not yet
     
  15. bitbutter

    bitbutter

    Joined:
    Jul 19, 2012
    Posts:
    60
    Oh weird, i thought i posted a reply to this already but it looks like it got eaten somewhere.

    Short version: Not all android phones accept multicast messages. The ones that don't (e.g. Motorola Moto G and moto E) won't 'auto discover' the server with the approach used in this script. Others will (e.g. Nexus 5).

    I ended up exposing an input field for non-auto-discovery phone users so they could manually enter the IP of the server if auto-connect wasn't happening.
     
    CrandellWS likes this.
  16. LondonStevey

    LondonStevey

    Joined:
    Jun 26, 2015
    Posts:
    33
    Hi - I'm a beginner with the whole multiplayer side of things and just trying to get my head around NetworkDiscovery. When I run this example the sphere gets spawned when I use the LAN Host and client. But when I use broadcast and and connect to a game nothing gets spawned, how can I spawn from the NetworkManager once connected through the Broadcast? Many Thanks!
     
  17. joostbos

    joostbos

    Joined:
    Feb 4, 2015
    Posts:
    64
    I am trying to get this working without the GUIs, both the Discovery GUI and the Network Manager GUI, but I can't figure out how.

    What I want to achieve is similar to @bitbutter 's question: connect my android phone to my desktop PC.

    So in high level code what I want is:
    #if UNITY_EDITOR || UNITY_STANDALONE
    Initialize()
    StartAsServer()
    #elif UNITY_ANDROID
    Initialize()
    StartAsClient()
    JoinGame()
    #endif

    That last JoinGame obviosuly does not exist. For that I would need to override OnReceivedBroadcast() as @HugoZandel mentioned. So I tried to make my own NetworkDiscovery class, see below, using the example OnBroadcastReceived from the Unity documentation. I then replaced @seanr 's NetworkManager with the default NetworkManager, but when I start the app first in the editor and then on my phone I don't see a playerSphere appear. I do get the debug message "Started as server" in the editor.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.Networking;
    4.  
    5. public class MyNetDiscovery : NetworkDiscovery
    6. {
    7.  
    8.     void Start ()
    9.     {
    10. #if UNITY_EDITOR
    11.         Initialize();
    12.         StartAsServer();
    13.         Debug.Log("Started as server");
    14. #elif UNITY_ANDROID
    15.         Initialize();
    16.         StartAsClient();
    17. #endif
    18.     }
    19.  
    20.     public override void OnReceivedBroadcast(string fromAddress, string data)
    21.     {
    22.         NetworkManager.singleton.networkAddress = fromAddress;
    23.         NetworkManager.singleton.StartClient();
    24.     }
    25. }
    26.  
    Thanks!

    Edit 2016-01-20: I did some more debugging and added a second scene to start when the connection is established (added MyOne as offline scene and two as online scene in the NetworkManager). I found that I do get to the end of the OnReceivedBroadcast, but the online scene never loads, neither on the server nor on the client.
    The same happens if I use the example's scene one. Also in that case I do not get to scene two. Although I am not completely sure I did everything right because it is very, very hard to see the GUI on my mobile phone, it is incredibly small. But I think I saw a button with connect to and an IP-address. And when I tapped on it the discovery buttons disappeared, although the network manager GUI was still on screen.
    I then tried to use a standalone version as client and the editor as server. Now I could read the button which said Game on ffff: and my PC's IP-address, but after clicking on it the same result. The broadcast GUI disappears but the Network Manager GUI remains on screen and still no second scene.
    Do I need to call something like NetworkManager.OnClientReady?? I would expect that this is handled by the Discovery component.
     
    Last edited: Jan 20, 2016
  18. joostbos

    joostbos

    Joined:
    Feb 4, 2015
    Posts:
    64
    After some more searching, cursing and retrying I found that I needed to start the NetworkManager on the server side as well. I added NetworkManager.singleton.StartServer() in the #if UNITY_EDITOR section after StartAsServer().
     
    Who-am-I likes this.
  19. chenyuchih

    chenyuchih

    Joined:
    Jun 3, 2015
    Posts:
    37
    Oops there seems some bug with NetworkDiscovery.
    When NetworkDiscovery.StartAsServer is invoked.
    The Object will become don't destroy on load
    Code (CSharp):
    1.  
    2.         public bool StartAsServer()
    3.         {
    4.             if (this.m_HostId != -1 || this.m_Running)
    5.             {
    6.                 if (LogFilter.logWarn)
    7.                 {
    8.                     Debug.LogWarning("NetworkDiscovery StartAsServer already started");
    9.                 }
    10.                 return false;
    11.             }
    12.             this.m_HostId = NetworkTransport.AddHost(this.m_DefaultTopology, 0);
    13.             if (this.m_HostId == -1)
    14.             {
    15.                 if (LogFilter.logError)
    16.                 {
    17.                     Debug.LogError("NetworkDiscovery StartAsServer - addHost failed");
    18.                 }
    19.                 return false;
    20.             }
    21.             byte b;
    22.             if (!NetworkTransport.StartBroadcastDiscovery(this.m_HostId, this.m_BroadcastPort, this.m_BroadcastKey, this.m_BroadcastVersion, this.m_BroadcastSubVersion, this.m_MsgOutBuffer, this.m_MsgOutBuffer.Length, this.m_BroadcastInterval, out b))
    23.             {
    24.                 if (LogFilter.logError)
    25.                 {
    26.                     Debug.LogError("NetworkDiscovery StartBroadcast failed err: " + b);
    27.                 }
    28.                 return false;
    29.             }
    30.             this.m_Running = true;
    31.             this.m_IsServer = true;
    32.             if (LogFilter.logDebug)
    33.             {
    34.                 Debug.Log("StartAsServer Discovery broadcasting");
    35.             }
    36.             Object.DontDestroyOnLoad(base.gameObject);
    37.             return true;
    38.         }
    I know that's necessary when enter game scene, we need a component to control lan game.

    But If I have two Scenes : LanGame, Online
    If I go back from Online scene to LanGame scene, NetworkDicovery object will become duplicated.
    My current workAround is write another script inherit NetworkDiscovery, and make it as singleton.
    When I enter LanGame scene, stop NetworkDiscovery if it's running.

    Does official expect we manually destroy the old NetworkDiscoery?
     
  20. belive_in

    belive_in

    Joined:
    Aug 18, 2015
    Posts:
    5
    Hi,the following question "Cannot open socket on ip {*} and port {7777}; check please your network, most probably port has been already occupied " ,do you have to solve the question?
     
  21. mimminito

    mimminito

    Joined:
    Feb 10, 2010
    Posts:
    780
    Could someone help with the following situation for me? I am able to get the discovery working fine, but after the initial connections and either the client or host drops, I would like to know how to handle this. Right now if the host quits the app and then restarts, the application is not able to broadcast on the same connection again and there seems to be a stale connection somewhere meaning the client is unable to see the host anymore.

    Basically I would like to be able to handle the following:
    1. Host starts broadcasting
    2. Client finds broadcast connects
    3. At some point host disconnects (app quit for example)
    4. Host restarts the app, needs to start broadcasting again so client can return and find broadcast again.

    Right now the host cant seem to be able to connect on the same port again, its like its being used and was not closed correctly when the host quit. Is there some method I need to call to ensure the connection is severed properly so on next start it will be able to connect it again?
     
  22. zeno490

    zeno490

    Joined:
    May 11, 2016
    Posts:
    2
    I had the same issue. Locally on my laptop, I would run the server and client just fine in two separate applications (editor + standalone) but it would fail to work when running the server on my laptop and a client on my android phone.

    As it turns out, the default NetworkDiscovery implementation does not work correctly out of the box. While it will show you the correct broadcasted IP when you listen in (with their debug GUI), when you attempt to join it, it always tries to join with 'localhost' as the network address.

    The solution for me was simply to override the default implementation and set the NetworkManager.singleton.networkAddress with the received broadcast address, more or less exactly as documented here: http://docs.unity3d.com/ScriptReference/Networking.NetworkDiscovery.html

    Note that you'll likely want to stop the broadcasting after your connection attempt to avoid reconnecting every time you receive a new broadcast.
     
    CrandellWS likes this.
  23. Hamed-Unity

    Hamed-Unity

    Joined:
    Jun 11, 2016
    Posts:
    1
    Hello every one
    i run the project
    i see the movement of server in client
    but the movement in client does not show in server??
    any idea??
    i use network transform

    and
    what is the difference between Lan host and Lan server

    i want to make a 2players game
     
    Last edited: Jun 11, 2016
  24. yaumulisnain

    yaumulisnain

    Joined:
    Oct 26, 2015
    Posts:
    4
    LAN Host = player as server and as client
    LAN Server = dedicated server only
     
    CrandellWS likes this.
  25. cadpeople

    cadpeople

    Joined:
    Nov 6, 2014
    Posts:
    21
    You're a life saver! This saved me from having to rewrite a lot of my networking to not use UNet :D
    THANK YOU!
     
  26. maniacanshul

    maniacanshul

    Joined:
    May 4, 2016
    Posts:
    3
    BUMP

    @Qwertyuiop1234 @seanr
    I am struggling with the same issue.

    Cannot open socket on ip {*} and port {7777}; check please your network, most probably port has been already occupied
    UnityEngine.Networking.NetworkManagerHUD:OnGUI()

    StartServer listen failed.

    Once a client disconnects, the server cannot start broadcasting again as it says the port is already being used. How do I close the port before disconnecting the current game or starting a new game.
     
  27. moco2k

    moco2k

    Joined:
    Apr 29, 2015
    Posts:
    294
    To get a better understanding of how it works, you can have a look into the Network Discovery source code.

    I remember that I had issues when I tried to call the StopBroadcast function from within my network manager and it was followed by something like StopHost afterwards. In this case, the StopHost function interrupted the proper completion of the StopBroadcast function. So, as a result, discovery was still broadcasting after quitting the game and it was not possible to start a new broadcast.

    Also, a related issue had been reported which is marked as being fixed for 5.5.
     
    Last edited: Oct 26, 2016
    Muckel likes this.
  28. Muckel

    Muckel

    Joined:
    Mar 26, 2009
    Posts:
    471
    hello,
    had a similar issue...
    here is how i fixed that...
    Code (CSharp):
    1. public override void OnStopHost() {
    2.         if(myNetworkDiscovery.running){
    3.             //myNetworkDiscovery.Initialize();
    4.             myNetworkDiscovery.StopBroadcast();
    5.         }
    6.         if (NetworkTransport.IsBroadcastDiscoveryRunning())
    7.              NetworkTransport.StopBroadcastDiscovery();
    8.              NetworkTransport.RemoveHost (0);
    9.         isRunning = false;
    10. //        Debug.Log("OnStopHost");
    11.     }
    NetworkTransport.RemoveHost (0);
    did the trick...
    M.
     
    CrandellWS likes this.
  29. eltronix

    eltronix

    Joined:
    Sep 6, 2016
    Posts:
    4
    @Muckel Wow it worked! Thank you, God bless your eternal soul.
     
    CrandellWS and Muckel like this.
  30. cpasjuste

    cpasjuste

    Joined:
    Apr 2, 2012
    Posts:
    154
    Hi @seanr, i'm not sure if it's the good place to report that but i think i may have found a problem in the "NetworkDiscovery.cs" source code.

    The problem is located in the "Update" function when "OnReceivedBroadcast" is called ( here ), there "you" are passing the "m_MsgInBuffer" as parameter while, i think, it should be "recv.broadcastData" to be passed, else the data size is not consistent between the sender/receiver (sender = broadcastData size, receiver = m_MsgInBuffer size).

    I noticed this while trying to encrypt/serialize a string to be used as broadcastData, the server will serialize the string making say 200 bytes in length, the client will receive the string but with a 512 bytes in lenght (m_MsgInBuffer size instead receivedSize).

    I hope i'm clear and this will be fixed soon so i can use stock sources !

    Thanks,
    Cpasjuste.
     
    Last edited: Jan 5, 2017
  31. moco2k

    moco2k

    Joined:
    Apr 29, 2015
    Posts:
    294
    @cpasjuste: Unet devs do not consequently check forum threads for bug reports. Also, I guess seanR is not an official member of the UNET staff since more than a year. So, you should really use the issue tracker to report the bug (I think you need to raise the ticket directly from the Unity editor). This will drastically increase chances that someone looks into it and that it actually gets fixed. The past has shown that this works quite well. While there are exceptions, describing potential bugs in the forum, however, usually does not work well.
     
    Last edited: Jan 12, 2017
    d1favero likes this.
  32. jcorace

    jcorace

    Joined:
    Apr 14, 2015
    Posts:
    2
    Hey @Qwertyuiop1234 @seanr @Muckel @eltronix do any of you have a simple example of restarting Broadcast Discovery on a server as I am having the same problems on 5.5.0f3.

    I tried Muckel's fix of adding NetworkTransport.RemoveHost (0) to OnStopHost() but this didn't fix anything.
    Thanks!
     
  33. Arulbabu

    Arulbabu

    Joined:
    Apr 12, 2013
    Posts:
    13
    [ WHY I CANT CLICK "LISTEN FOR BROADCAST" MORE THAN ONE CLIENT ]

    Hi all..

    I just tried the project file you provided. i have a small problem. when i run 3 instances of the output exe...let say A,B,C

    1.in A, i clicked lan Host
    2.in B, i clicked lan Client
    3.in C,i clicked lan Cleint

    works perfect...but

    1.when i click Initialize broadcasting in A ,B,C
    2. and i clicked Start broadcasting in A
    3. and i clicked Listen for broadcasting in B, and it shows the A's Game... but the problem is

    why i can click Listen for broadcasting in C... it's not getting connected...

    or i understand totally wrong... Please help me in this.

    Thanks ABC.png
     
  34. Xpoint

    Xpoint

    Joined:
    Oct 27, 2016
    Posts:
    1
    hey @Arulbabu
    I think It is a bit late (toooooooooooooooooooo late)
    but if anyone came across a similar issue not being able to open multiple "Listen for broadcasting" on same machine
    the problem will be that the first time you will reserve the port of listening for the broadcast so the next time, you won't be able to listen on the same port (I don't know if there is a way to fix it like to use another port; and I don't there will be one too)
     
  35. Akki-bhatt

    Akki-bhatt

    Joined:
    Jul 8, 2017
    Posts:
    19
    hey @Arulbabu @Xpoint

    It's been too late but I feel it might help you for network discovery.
    go here.
     
    xVergilx likes this.
  36. degeta

    degeta

    Joined:
    Sep 14, 2016
    Posts:
    2
    In the screenshot, it shows a simple game. in this game P1 is the user and P2 acts like a bot. P1 has the option to choose 3 buttons at the bottom and when he selects any one of those, it is compared with P2’s choice(P2’s option is chosen automatically in the script using Random()).So as of now its like playing with CPU opponent and not with a real player. So i wanted to make this a multiplayer, where the opponent will choose one of the options and player will also choose and a winner will be decided based on a logic. I have gone through the UNET docs, completed the multiplayer sample its connecting well and fine. I tested it on the two phones and its working too. So can anyone help me in creating this multiplayer in unity? It would be really helpful . The network connectivity I’m prefering is just local Wifi hotspot and not internet.
     

    Attached Files:

  37. Muckel

    Muckel

    Joined:
    Mar 26, 2009
    Posts:
    471
    Hello @cpasjuste,
    do ya know if the problem is fixed?
    and can you post plz a example code how to fix it?
    ,many many thx
    M.
     
  38. surajsirohi1008

    surajsirohi1008

    Joined:
    Jun 21, 2016
    Posts:
    267
    I ran an instance of the game using the file attached here on my laptop and other instance on my android phone. I turn on hotspot, connect my laptop to phone's hotspot, start broadcasting on phone and listen on laptop, I see "game available at 192.168.43.1", when I click it, it says "connecting". The discovery is working, but the game scene (online scene) never starts, the clients doesn't connect. What do I do?
     
    mexdesigns1 likes this.
  39. Arulbabu

    Arulbabu

    Joined:
    Apr 12, 2013
    Posts:
    13

    Thanks Bro :)
     
  40. Arulbabu

    Arulbabu

    Joined:
    Apr 12, 2013
    Posts:
    13
    Thanks Bro :)