TCP Server/Client with Laptop/Phone doesn't work with devices, does work on local host.

I’m trying to make a simple application which uses TCP to send a few strings from a client application (Android phone) to a server application (Macintosh). I uses two scenes, one for each of the applications.

I tested this functionality by building the client and running it after I clicked the ‘Play’ button in the unity editor for the server, and it worked, I was able to send the desired strings from one application to the other. The next step was to build the client application for android and use it on an android device while running the server in the Unity editor as done before, changing the IP address from local host to my laptop’s IP address. Both devices were connected to the same wifi network. When I did this, I would get this message in my android studio monitor:

Socket error: Connection refused
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object)
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
SendPic:connectToServer() (at…)

Here is the code for the client:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using UnityEngine;

public class SendPic : MonoBehaviour {

	private bool connected = false;
	private TcpClient socket;
	private NetworkStream stream;
	private StreamWriter writer;
	private StreamReader reader;
	public string IP = "localhost";
	public int port = 8888;
	private int count = 0;

	public void connectToServer()
	{
		if (connected)	//already connected
			return;

		try
		{
			socket = new TcpClient(IP,port);
			stream = socket.GetStream ();
			writer = new StreamWriter (stream);
			reader = new StreamReader (stream);
			connected = true;
			Debug.Log("Connected to: " + IP + ":" + port.ToString());
		}
		catch (Exception e)
		{
			Debug.Log ("Socket error: " + e.Message);
		}
	}

	private void Send()
	{
		String Data = Time.time.ToString();
		if (!connected)
			return;
		writer.WriteLine (Data);
		writer.Flush ();
		count = count + 1;
	}

	void Start ()
	{
		Invoke ("connectToServer", 1.0f);
		InvokeRepeating ("Send", 0.0f, 0.5f);
	}

	void Update () 
	{
		if (count >= 20)
			CancelInvoke ();
	}
}

Here is the server code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using UnityEngine;


public class ReceivePic : MonoBehaviour 
{
	public int port = 8888;
	private List<ServerClient> clients;
	private List<ServerClient> disconnects;
	private TcpListener server;
	private bool started = false;

	private void Start()
	{
		clients = new List<ServerClient> ();
		disconnects = new List<ServerClient> ();

		try
		{
			server = new TcpListener(IPAddress.Any, port);
			server.Start();

			StartListening();
			started = true;
			Debug.Log("Server started on port: " + port.ToString());
		}
		catch (Exception e)
		{
			Debug.Log("Socket error: " + e.Message);
		}
	}

	private void StartListening() 
	{
		server.BeginAcceptTcpClient (AcceptTcpClient, server);
	}

	private void AcceptTcpClient(IAsyncResult ar) 
	{
		TcpListener listener = (TcpListener)ar.AsyncState;
		clients.Add (new ServerClient (listener.EndAcceptTcpClient (ar)));
		Debug.Log("New connection established");
		StartListening ();
	}

	private bool isConnected(TcpClient c)
	{
		try 
		{
			if(c != null && c.Client != null && c.Client.Connected)
				return true;
			else
				return false;
		}
		catch
		{
			return false; //not able to reach client
		}

	}

	private void onIncomingData(ServerClient c, string data)
	{
		Debug.Log (c.clientName + "Has sent the following message: " + data);
	}


	private void Update()
	{
		if (!started)
			return;
		
		foreach (ServerClient c in clients)
		{
			//is the client still connected
			if (!isConnected (c.tcp))
			{
				c.tcp.Close ();
				disconnects.Add (c);
				continue;
			}

			//check for message
			NetworkStream s = c.tcp.GetStream();
			if (s.DataAvailable)
			{
				StreamReader reader = new StreamReader (s, true);
				string data = reader.ReadLine ();

				if (data != null)
					onIncomingData (c, data);
			}
		}
	}
}

public class ServerClient
{
	public TcpClient tcp;
	public string clientName;

	public ServerClient(TcpClient clientSocket) 
	{
		clientName = "Guest";
		tcp = clientSocket;
	}
}

I made that in player settings for the android client, internet access is required.

I’m fairly new to networking so I’m hoping that there might be a simple fix that I can use. I’ve reproduced this problem on my school wifi network and through a mobile hotspot using a separate phone.

Well “Connection refused” sound a lot like you have a firewall setup which might be blocking the connection. So check your laptop’s OS setting. It’s also possible that your wifi is actively filtering / blocking any traffic that is not authorized. This is common for school networks.