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 connect button it connects to server and works fine. Now when I clieck on Disconnect button and again click on connect button to make the connection, it's throwing an exception on tcpclient.connect line. I don't understand why or how can I solve it, Please suggest.
Thnx,
A