Tcpclient C# Windows Form how to close and open the same connection

Asked

Viewed 128 times

0

I am developing a Windows Form C# application and I am using Tcpclient to carry out communication within my internal network, in some moments I need to close an existing connection and after a few minutes reopen this connection, but I’m having trouble performing this procedure.

First I start Tcpclient.

TcpClient clientSocket = new TcpClient();
clientSocket.Connect(textBox1.Text, int.Parse(textBox2.Text));

At some point I want to close this connection, I tried Dispose() and Close().

clientSocket.Dispose();
clientSocket.Close();

And then wish in a moment to reconnect by performing the following commands

 if (!clientSocket.Connected)//Verifico se a conexão esta ativa
 {
      clientSocket = new TcpClient();//Estáncio novamente clientSocket
      clientSocket.Connect(textBox1.Text, int.Parse(textBox2.Text));//Mas dá exceção nesta linha.
 }

With all procedures adopted above is returned an Exception

System.Net.Sockets.Socketexception: 'A socket operation has been attempted on an inaccessible host xx.xx.x.xx:8080', in the line below

clientSocket.Connect(textBox1.Text, int.Parse(textBox2.Text));

This means that the connection really gets instantiated by not letting makes a new connection.

How to carry out this procedure, so that you have the freedom to carry out these procedures ?

1 answer

2


The error is due to not having properly disconnected the previous connection and making a new connection using the same port.

To close the connection use

NetworkStream stream = clientSocket.GetStream();
stream.close();
clientSocket.close();

When you want to connect again create a new instance and use Connect(....) of that instance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.