Hi,
I have a server which is running on a port and is waiting for connections.
The connect part is working fine but when i click on "Disconnect" button, it is actually disconnecting.
Here is the part of my code
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (btnDisconnect.Enabled == true)
{
btnDisconnect.BackColor = System.Drawing.Color.DarkBlue;
btnDisconnect.ForeColor = System.Drawing.Color.AntiqueWhite;
Listener l = new Listener(ipAddr);
try
{
txtLog.AppendText("Stopping listener");
l.disConnect();
txtLog.AppendText("stopped");
}
catch (Exception)
{
txtLog.AppendText("Unhandled Listener Close");
}
}
}
Here is the listener class
class Listener
{
private IPAddress ipAddress;
private TcpClient tcpClient;
private TcpListener tcpListener;
private Thread thrListener;
bool ServRunning = false;
public static event StatusChangedEventHandler StatusChanged;
private static StatusChangedEventArgs e;
public Listener(IPAddress address)
{
ipAddress = address;
}
public static void OnStatusChanged(StatusChangedEventArgs e)
{
StatusChangedEventHandler statusHandler = StatusChanged;
if (statusHandler != null)
{
statusHandler(null, e);
}
}
public void startListening()
{
IPAddress ipaLocal = ipAddress;
tcpListener = new TcpListener(ipaLocal, 13);
tcpListener.Start();
ServRunning = true;
thrListener = new Thread(KeepListening);
thrListener.Start();
}
private void KeepListening()
{
while (ServRunning == true)
{
tcpClient = tcpListener.AcceptTcpClient();
e = new StatusChangedEventArgs("Connected");
OnStatusChanged(e);
bool m = true;
while (m)
{
byte[] bytes = new byte[2560];
NetworkStream stream = tcpClient.GetStream();
stream.Read(bytes, 0, bytes.Length);
string mstrMessage = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
e = new StatusChangedEventArgs(mstrMessage);
OnStatusChanged(e);
XmlDocument myxmlDoc = new XmlDocument();
myxmlDoc.LoadXml(mstrMessage);
string message = myxmlDoc.SelectSingleNode("Connect/@message").InnerText;
message = Regex.Replace(message, @"\t|\n|\r", "");
if (message.Equals("send"))
{
DriveInfo1 d = new DriveInfo1();
string mstrDriveResponse = d.getDrive();
byte[] bytesSent = Encoding.ASCII.GetBytes(mstrDriveResponse);
stream.Write(bytesSent, 0, bytesSent.Length);
string mstrBuildResponse = d.Installed();
byte[] byteSent = Encoding.ASCII.GetBytes(mstrBuildResponse);
stream.Write(byteSent, 0, byteSent.Length);
}
else
{
string mstrResponse = @"<?xml version=""1.0"" encoding=""utf-8""?><Response message=""Unable to parse xml"">";
byte[] bytesSent = Encoding.ASCII.GetBytes(mstrResponse);
stream.Write(bytesSent, 0, bytesSent.Length);
}
m = false;
stream.Close();
}
}
}
public void disConnect()
{
tcpClient.Close();
tcpListener.Stop();
}
}
Please help to rectify the error!!
Thanks :)