I have these here methods:
private void connectToServer() {
client = new TcpClient(SERVER_IP, PORT_NO);
nwStream = client.GetStream();
writer = new StreamWriter(client.GetStream());
writer.AutoFlush = true;
connected = true;
getDataFromServer();
rtb_inputField.Select();
if (getDataTimer == null) {
getDataTimer = new System.Timers.Timer();
getDataTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
getDataTimer.Interval = 1000;
getDataTimer.Enabled = true;
}
}
private void disconnectFromServer() {
if (connected) {
writer.WriteLine("quit");
getDataTimer.Enabled = false;
getDataTimer.Dispose();
getDataTimer = null;
Thread.Sleep(1000); //Wait 1 second
nwStream.Close();
client.Close();
rtb_outputWindow.AppendText("\n\nClient: Disconnected.");
}
connected = false;
}
private void getDataFromServer() {
if (connected) {
new Thread(() => {
Thread.CurrentThread.IsBackground = true;
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int readData = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
updateOutputWindow(Encoding.Default.GetString(bytesToRead, 0, readData));
}).Start();
}
}
private void updateOutputWindow(string text) {
string newText = string.Empty;
if (InvokeRequired) {
Invoke(new MethodInvoker(delegate () {
updateOutputWindow(text);
}));
}
else {
newText = startRTFString;
newText += rtb_outputWindow.Rtf;
newText += replaceAnsiColorCodes(text);
rtb_outputWindow.Rtf = newText;
}
}
private void OnTimedEvent(object source, ElapsedEventArgs e) {
if (connected) {
getDataFromServer();
}
}
This all works, but something is wrong. When I disconnect the outputWindow gets a lot of newlines before finally saying "Client: Disconnected." The longer I stay connected to the server, the longer it takes to disconnect.
I believe the timer has something to do with this issue. The timer's job is to continuously request data from the server, and output it if any is received. Is there a better way of doing it? Perhaps "wait for server to send data" - in case nothing gets sent for several seconds, I won't have to hammer the server for requests.
Is the new thread in the getDataFromServer method taken care of by the garbage collector? Or do I need to dispose it somehow? (So that I don't end up creating a whole bunch of background threads.)