Reputation: 21
I am writing an application to send/receive some data to and from a server. I need to make a connection before sending some data and need to keep it open so that user can send data continuously. The user can close the connection at any time by clicking on disconnect button. I created 2 buttons, one to connect and one to disconnect. Code behind Disconnect button is as below:-
private void button1_Click(object sender, EventArgs e)
{
if (tcpclnt.Connected)
{
tcpclnt.Client.Disconnect(false);
stm.Close();
}
else
{
MessageBox.Show("Not Connected");
}
}
code behind connect button is as below:-
public ASCIIEncoding asen = new ASCIIEncoding();
public TcpClient tcpclnt = new TcpClient();
public NetworkStream stm;
private void Connect_Click(object sender, EventArgs e)
{
if (!tcpclnt.Connected)
{
tcpclnt.Connect("XX.XX.XX.XX", 5500);
MessageBox.Show("Connected to server");
stm = tcpclnt.GetStream();
string sysname = "000B0000" + SystemName.Text.ToString();
byte[] sys1 = asen.GetBytes(sysname);
sys1[0] = 0; sys1[1] = 0;
sys1[2] = 0; sys1[3] = 0xB;
sys1[4] = 0; sys1[5] = 0;
sys1[6] = 0; sys1[7] = 0;
try
{
stm.Write(sys1, 0, sys1.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
MessageBox.Show("Error in Sending data");
}
if (stm.DataAvailable)
{
try
{
byte[] bb = new byte[600];
int k = 8;
k = stm.Read(bb, 0, bb.Length);
string value = ASCIIEncoding.ASCII.GetString(bb, 8, k - 8);
MessageBox.Show(value.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
MessageBox.Show("Error in Reading data");
}
}
}
else {
MessageBox.Show("Already Connected");
}
}
Now, when I click on Disconnect button and again click on connect button, it's throwing an exception on tcpclient.connect line. I don't understand why or how can I solve it.
Upvotes: 1
Views: 8140
Reputation: 2809
Not an expert on this topic, but I think a possible solution would be to gracefully close the connection using tcpclnt.Close(). If you don't do this or let the garbage collector do it ungracefully, then you can't reconnect (I think). Close the stream, then close the tcpclnt rather than disconnect.
tcpclnt.GetStream().Close();
tcpclnt.Close();
Also, don't use tcpclnt.Connected to check if there's a connection. Just simply Close it.
EDIT
The above doesn't work. I don't know how to reuse the socket. This is how I got it to work...
private void DisconnectButton_Click(object sender, EventArgs e)
{
tcpclnt.Close();
tcpclnt = new TcpClient();
}
You mentioned that re-instantiating the object creates additional threads. This might be true as I'm unsure how to test for this. I opened up the windows resource monitor and watched the thread count for the app and it didn't show an additional thread opening each time.
Upvotes: 1