Networking Issue: Cannot connect to server

Overview

I am trying to make a multi-player game and wish to connect the Client to the Server. However, even though I am not getting any errors when coding, the Client is unable to connect to the Server and returns this error “The connection request to [IP ADDRESS] failed. Are you sure the server can be connected to?”

I have tried looking up many different threads with the same problem but I still cannot find the answer to the issue.


Code for Server

//Variable(s)
var IP : String = "42.60.8.21";
var port : int = 28000;
var maxConnections : int = 10;

//Function(s)
function OnGUI() {

if (Network.peerType == NetworkPeerType.Disconnected) {

if (GUILayout.Button("Initialise Server")) {
Network.InitializeServer(maxConnections, port, false);
Debug.Log("Server Initialised");
}

if (GUILayout.Button("Quit")) {
Application.Quit();
}


} else {
if (GUILayout.Button("Terminate Server")) {
Network.Disconnect();
}

GUILayout.Label("Current Connections: " + Network.connections.Length);

}

}

function OnPlayerDisconnected(client : NetworkPlayer) {

Debug.Log("Disconnecting Clients");
Network.RemoveRPCs(client);

}

function OnDisconnectedFromServer() {

Debug.Log("Server Terminated");

}

Code for Client

//Variable(s)
var ServerIP : String = "42.60.8.21";
var ServerPort : int = 28000;
var myIP : String = "42.60.8.21";
var myPort : int = 28001;

//Function(s)
function OnGUI() {

if(Network.peerType == NetworkPeerType.Disconnected) {

if (GUILayout.Button("Quit")) {
Application.Quit();
}

if (GUILayout.Button("Start")) {
Network.Connect(ServerIP, ServerPort);
}

} else {
if (GUILayout.Button("Disconnect")) {
Network.Disconnect();
}

}

}

function OnConnectedToServer() {

print("Connected");

}

Thanks in advance!

I have been stuck at this for weeks and I cannot seem to figure out a solution it. Any help would be greatly aprreciated!

In order for a connection to work between your server and client the following must happen:

  1. If your network is on a router then you need to set a port foward to the local ip address of the machine the server is running on. ex. 192.168.0.3 ports 28000 - 29000; (I found out that some unity games need more than 1 port forwarded to work, so I just port forward a series of ports to be sure.)
  2. You can find the local ip of machine by cmd and Ipconfig.
  3. If your client and server our on the same machine (for testing) you can use 127.0.0.1.
  4. Make sure your firewall allows your program to communicate through the port or ports you are communicating through.
  5. Make sure you use RPC and the networkview classes correctly to communicate the information between server and client.
  6. Make sure your IP address hasn’t change. google “What is my IP” and it should quickly give you it.