Answer the question
In order to leave comments, you need to log in
How to write a TCP client-server application correctly so that it can work not only on the local network?
I wrote a simple client-server application based on the TcpListener and TcpClient classes. Everything works fine on the local network, but when I turn on the server on my computer, and a friend starts the client on his computer, I get the following error: "An attempt to establish a connection was unsuccessful, because the required response was not received from another computer in the required time , or an already established connection was terminated due to an incorrect response from an already connected computer"
PS: I have a static ip, I opened ports on my computer and on the computer with the client.
//Код сервера
static void Main(string[] args)
{
Console.Write("Введите порт для прослушивания сервером: ");
string enteredPort = Console.ReadLine();
TcpListener tcpListener = null;
try
{
int port = Convert.ToInt32(enteredPort);
tcpListener = new TcpListener(IPAddress.Any ,port);
tcpListener.Start();
}
catch (FormatException)
{
Console.WriteLine("Неправильно введён ip или порт");
}
catch (SocketException)
{
Console.WriteLine("Ошибка подключения(((");
}
TcpClient tcpClient = tcpListener.AcceptTcpClient();
while (true)
{
if (tcpClient.Connected)
{
Console.WriteLine("Успех!!!");
}
}
}
//Код клиента
static void Main(string[] args)
{
Console.Write("Введите ip сервера: ");
string serverIp = Console.ReadLine();
Console.Write("Введите порт сервера: ");
string serverPort = Console.ReadLine();
var tcpClient = new TcpClient();
try
{
IPAddress iPAddress = IPAddress.Parse(serverIp);
int port = Convert.ToInt32(serverPort);
tcpClient.Connect(new IPEndPoint(iPAddress, port));
}
catch (FormatException)
{
Console.WriteLine("Неправильно введён ip или порт");
}
catch (SocketException ex)
{
Console.WriteLine("Ошибка подключения(((" + ex.Message);
}
while (true)
{
if (tcpClient.Connected)
{
Console.WriteLine("Успех!!!");
}
string ki = Console.ReadLine();
if (ki == string.Empty)
break;
}
Answer the question
In order to leave comments, you need to log in
"I have a static ip, I opened ports both on my computer and on the computer with the client."
the static ip is clearly on your router, most likely you need to do port forwarding from it to your computer.
There is no need to open the port on the client computer.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question