I'm having trouble establishing a TCP connection between two devices connected on the same wifi network (a PC and a mobile), the code seems to be fine, but the client (in my case, the phone) keeps trying to connect and the server (the pc ), wait for a connection and in the end nothing happens. I tried to configure my firewall on the PC, but it still doesn't work. I would like that these applications could work on other PCs without configuring so much and in a very simple way, since it is a tool to expose in the university.
I also gave him the permissions to connect to the internet to the mobile application
Here I leave the code of the pc:
class TcpServerCode
{
IPEndPoint ipEnd;
Socket sock;
public TcpServerCode(int port)
{
ipEnd = new IPEndPoint(IPAddress.Any, port);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
public static string curMsg = "Stopped";
public void StartServer()
{
try
{
curMsg = "Starting...";
sock.Listen(100);
curMsg = "Running and waiting to receive file.";
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024];
int receivedBytesLen = clientSock.Receive(clientData);
curMsg = "Receiving data...";
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string getStr = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
Form1.Singletone.ConsoleLog(getStr);
clientSock.Close();
}
catch (Exception ex)
{
curMsg = "Error.";
}
}
}
And here the mobile:
class TcpClientCode
{
public static string curMsg = "Idle";
public static void SendComand(string comand)
{
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
byte[] fileNameByte = Encoding.ASCII.GetBytes(comand);
byte[] clientData = new byte[4 + fileNameByte.Length];
curMsg = "Connection to server ...";
clientSock.Connect(ipEnd);
curMsg = "Command sending...";
clientSock.Send(clientData);
curMsg = "Disconnecting...";
clientSock.Close();
curMsg = "transferred.";
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}