Start Server or Join Existing Server as client automatically
I'm trying to get this small application working, where a game starts the server and any other instances game when run, directly joins in as the client, without any GUI.
For now, I could do so, with using a custom NetworkManager and custom NetworkDiscovery. But here's the problem. One client connects automatically, but when i open a another instance to join in as client, I get the following error.
Cannot open socket on ip {*} and port {57777}; check please your network, most probably port has been already occupied
NetworkDiscovery StartAsClient - addHost failed
Please Help.
CustomNetworkManager.cs
public class CustomNetworkManager: NetworkManager {
private bool connected = false;
public NetworkDiscovery discovery;
private void OnGUI(){
if (!connected)
{
if (GUILayout.Button("Start Server"))
NetworkManager.singleton.StartServer();
}
else
GUILayout.Label("Connected");
}
void Start(){
NetworkManager.singleton.networkPort = 7777;
NetworkManager.singleton.networkAddress = "127.0.0.1";
}
public override void OnStartServer(){
discovery.StopBroadcast();
Debug.Log("Start Server Broadcast....");
discovery.broadcastData = networkPort.ToString();
discovery.StartAsServer();
base.OnStartServer();
connected = true;
}
public override void OnClientConnect(NetworkConnection conn){
Debug.Log("Client Connected to server");
base.OnClientConnect(conn);
connected = true;}
}
CustomNetworkDiscovery.cs
public class CustomDiscovery : NetworkDiscovery {
void Start() {
Initialize();
if (!NetworkServer.active)
StartAsClient();
}
public override void OnReceivedBroadcast(string fromAddress, string data) {
Debug.Log("Received Broadcast Message with Data " + fromAddress);
NetworkManager.singleton.networkAddress = fromAddress;
if (!NetworkClient.active)
NetworkManager.singleton.StartClient();
}
}
Your answer
Follow this Question
Related Questions
unity NetworkingLobbyManager problem 0 Answers
Using joints with UNet Not Working Correctly 0 Answers
Designing a multiplayer lobby for LAN 1 Answer
Day/Night cycle turns black at night and how to Serialize it rightly? 0 Answers
Photon Networking - How to move all players from game scene to current room scene? 0 Answers