I'm creating a massmailing program basically, and the problem is that if I do it without threads, it obviously freeze and it needs to be able to show user the progress. Without using another class/object it works perfectly fine.
I get a stackoverflowexception:
{Cannot evaluate expression because the current thread is in a stack overflow state.}
on
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
NOTICE: This can probably be missleading because I haven't even created the thread yet but it still get's stackoverflowexception.
This is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Windows;
using System.Net.Mail;
namespace Mass_Mail
{
public partial class Form1 : Form
{
Form2 frm = new Form2();
Worker work = new Worker();
public List<String> succed = new List<String>();
public List<String> failed = new List<String>();
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog(); //Skapa och definiera openfiledialog
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //sätt startmappen till skrivbordet
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; //textfiler.
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
textBox1.Text = openFileDialog1.FileName.ToString();
using (StreamReader sr = new StreamReader(openFileDialog1.FileName)) {
String line;
while ((line = sr.ReadLine()) != null)
{
textBox2.AppendText(line + Environment.NewLine);
}
}
}
catch (Exception ex) {
MessageBox.Show("Kunde inte öppna " + ex.Message);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
frm.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
frm.comboBox1.SelectedIndex = 0;
}
private void button4_Click(object sender, EventArgs e)
{
// work.sendmail(textBox6.Text);
}
}
public class Worker
{
public void DoWork()
{
string[] lines = frm1.textBox2.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++)
{
sendmail(lines[i]);
}
}
Form1 frm1 = new Form1();
Form2 frm2 = new Form2();
public void sendmail(String mail)
{
try
{
SmtpClient client = new SmtpClient(frm2.textBox1.Text, int.Parse(frm2.textBox2.Text));
MailMessage msg = new MailMessage(frm1.textBox3.Text, mail);
client.Timeout = decimal.ToInt32(frm2.numericUpDown1.Value);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("", "");
switch (frm2.comboBox1.SelectedIndex)
{
case 0:
client.EnableSsl = true;
break;
case 1:
client.EnableSsl = false;
break;
}
msg.Subject = frm1.textBox4.Text;
msg.Body = frm1.textBox5.Text;
msg.BodyEncoding = UTF8Encoding.UTF8;
msg.IsBodyHtml = true;
client.Send(msg);
frm1.succed.Add(mail);
frm1.label6.Text = "Lyckades: " + frm1.succed.Count.ToString();
}
catch (System.Net.Mail.SmtpException ex)
{
MessageBox.Show("ERROR! " + ex);
frm1.failed.Add(mail);
frm1.label7.Text = "Misslyckades: " + frm1.failed.Count.ToString();
}
catch (System.FormatException e)
{
MessageBox.Show("ERROR! " + e);
frm1.failed.Add(mail);
frm1.label7.Text = "Misslyckades: " + frm1.failed.Count.ToString();
}
}
}
}
I'm going to create a thread of DoWork. I have never done anything like this and I know that the code is pretty bad at the moment. Any kind of help is highly appreciated.
I'm also really new to C# and multi-threading at all.
Form2 only consists of textboxes etc to contain the SMTP settings, no code there.
EDIT:
If I don't create a new object
Worker work = new Worker();
it works perfectly fine!
In your form you create a new worker:
Worker work = new Worker();
But when you create a worker you create a new form:
Form1 frm1 = new Form1();
And it goes on and on until it breaks.
Remove Worker work = new Worker(); from Form 1. Change your Form 1 constructor like this:
Worker _worker;
public Form1()
{
InitializeComponent();
_worker = new Worker(this);
}
Change your worker like this:
public class Worker
{
Form1 _form1;
public Worker(Form1 form1)
{
_form1 = form1;
}
...
And remove Form1 frm1 = new Form1() from your worker.
Related
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;
namespace DownloadFiles
{
public partial class Form1 : Form
{
Stopwatch sw = new Stopwatch();
Stopwatch stopwatch = new Stopwatch();
string filesdirectory = "Downloaded_Files";
string mainurl = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/";
List<string> parsedlinks = new List<string>();
string path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
List<string> results = new List<string>();
//StreamWriter w = new StreamWriter(#"e:\monitordetector.txt");
public Form1()
{
InitializeComponent();
//DetectScreenName();
label3.Text = "";
label4.Text = "";
label5.Text = "";
label7.Text = "";
button2.Enabled = false;
button3.Enabled = false;
filesdirectory = Path.Combine(path_exe, filesdirectory);
if (!Directory.Exists(filesdirectory))
{
Directory.CreateDirectory(filesdirectory);
}
else
{
if (IsDirectoryEmpty(filesdirectory) == false)
{
button3.Enabled = true;
}
}
}
public bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}
private string downloadhtml(string url)
{
backgroundWorker1.ReportProgress(0, "Downloading Main Url");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Proxy = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string html = sr.ReadToEnd();
sr.Close();
response.Close();
StreamWriter w = new StreamWriter(path_exe + "\\page.html");
w.Write(html);
w.Close();
return html;
}
int Counter = 0;
int percentage = 0;
int total = 0;
int countfiletodownload = 0;
bool processStatus = false;
private void Parseanddownloadfiles()
{
downloadhtml(mainurl);
if (bgw.CancellationPending == false)
{
backgroundWorker1.ReportProgress(0, "Parsing Links");
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(path_exe + "\\page.html");
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("US"))
{
string url = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/" + hrefValue;
parsedlinks.Add(url);
if (bgw.CancellationPending == true)
return;
}
}
countfiletodownload = parsedlinks.Count;
total = parsedlinks.Count;
backgroundWorker1.ReportProgress(0, "Downloading Files");
processStatus = true;
for (int i = 0; i < parsedlinks.Count && bgw.CancellationPending == false; i++)
{
try
{
using (WebClient client = new WebClient())
{
sw.Start();
Uri uri = new Uri(parsedlinks[i]);
string filename = parsedlinks[i].Substring(71);
//client.DownloadFile(parsedlinks[i], filesdirectory + "\\" + filename);
client.DownloadFileAsync(uri, filesdirectory + "\\" + filename);
Counter += 1;
percentage = Counter * 100 / total;
string filenametoreport = filename.Substring(1);
countfiletodownload--;
backgroundWorker1.ReportProgress(percentage, filenametoreport);//countfiletodownload, filenametoreport);
}
}
catch (Exception err)
{
string error = err.ToString();
}
}
}
}
/*void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// Calculate download speed and output it to labelSpeed.
if (label12.InvokeRequired)
{
label12.Invoke(new MethodInvoker(delegate
{
label12.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
}));
}
// Update the progressbar percentage only when the value is not the same.
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(new MethodInvoker(delegate
{
progressBar1.Value = e.ProgressPercentage;
}));
}
// Show the percentage on our label.
if (label13.InvokeRequired)
{
label13.Invoke(new MethodInvoker(delegate
{
label13.Text = e.ProgressPercentage.ToString() + "%";
}));
}
// Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading
if (label14.InvokeRequired)
{
label14.Invoke(new MethodInvoker(delegate
{
label14.Text = string.Format("{0} MB's / {1} MB's",
(e.BytesReceived / 1024d / 1024d).ToString("0.00"),
(e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
}));
}
}*/
/*void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
// Reset the stopwatch.
sw.Reset();
if (e.Cancelled == true)
{
MessageBox.Show("Download has been canceled.");
}
else
{
//MessageBox.Show("Download completed!");
}
}*/
private void Form1_Load(object sender, EventArgs e)
{
}
BackgroundWorker bgw;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
bgw = (BackgroundWorker)sender;
if (bgw.CancellationPending == true)
{
return;
}
else
{
Parseanddownloadfiles();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState.ToString() == "Downloading Main Url")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Parsing Links")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Downloading Files")
{
label7.Text = countfiletodownload.ToString();//parsedlinks.Count.ToString();
label3.Text = e.UserState.ToString();
}
if (processStatus == true)
{
if (e.UserState.ToString() != "Downloading Files")
{
label4.Text = e.UserState.ToString();
label7.Text = countfiletodownload.ToString();
progressBar1.Value = e.ProgressPercentage;
/*using (var bitmap = new Bitmap(this.Width, this.Height))
{
this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(#"e:\screens\ss.gif" + countscreenshots, System.Drawing.Imaging.ImageFormat.Gif);
countscreenshots += 1;
}*/
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
string fff = null;
}
label3.Text = "Operation Cancelled";
button1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
label3.Text = "Cancelling Operation";
backgroundWorker1.CancelAsync();
button2.Enabled = false;
timer1.Stop();
stopwatch.Stop();
stopwatch.Reset();
}
private void button1_Click(object sender, EventArgs e)
{
label3.Text = "";
label4.Text = "";
label7.Text = "";
backgroundWorker1.RunWorkerAsync();
timer1.Start();
stopwatch.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
Process.Start(filesdirectory);
}
private void timer1_Tick(object sender, EventArgs e)
{
label5.Text = string.Format("{0:hh\\:mm\\:ss}", stopwatch.Elapsed);
}
}
}
for some reason the code inside the event make the whole application to not to be async. If I comment the code not to use it then it's async working fine.
I also want to use the client_DownloadProgressChanged that now is not in use to show and display the downloading infos.
Like speed time using progressBar info per current file download and info for overall progress download.
No*, you do not need to Invoke in a BackgroundWorker's ProgressChanged event. DoWork is run on a background thread but the thread that executes the code inside ProgressChanged (and the other event handlers on a backgroundworker) is done by the thread that created the backgroundworker, which should be the same as the thread that created the other ui controls and hence no Invokation required
*Having said this, pay close attention to the part where I said that BGW will run the ProgressChanged event using the thread that created the BGW. In most cases this will be the UI thread.. if you've used a thread other than the UI thread to create the BGW then YES, invokation would be required. Create the BGW on the UI thread along with all your other controls, if you want a simple life. For the rest of my advice I'll assume this is what you've done.
I wasn't able to understand exactly your problem, but remember that it's the UI thread that runs the event handler. If you send that thread off doing some long task or blocking operation as part of your efforts to update the labels in the UI then it will make the application seem hung. You must let the UI thread complete the code in the event handler as soon as possible. If it will need to access data that is from a long or blocking operation, either have the DoWork calculate the data before it raises its progress, or use another method to avoid blocking the UI thread, like async task pattern
Note that Invoke and blocking the ui are completely different things. Windows controls may only be accessed by the thread they were created with. If another thread wants to access the control, it should use Invoke to cause the ui thread to do the work instead. This is a very different thing to the notion of not jamming up your ui by using the UI thread to read 50 gigabytes from a slow server and not using something that lets it quickly get back to its job of processing window messages and keeping the app responsive
So basically I used two speech recognition engines(speechrecog & speechrecog1) and one speech synthesizer. When the speechrecog is asked a question like how are you
it then replies I am fine (if the computer picks 2 from the two numbers 1,2). Then it initializes the second speech recognition engine. When it does its stuff. It then turns the second one off and the first one on again. But the problem is when using the second speech recognition engine it repeats( speech synthesizer) the number of times I have tried the second speech recognition engine out.
Here's my code for that form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Threading;
namespace Project_Juliet
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}
class FullScreen
{
public void EnterFullScreenMode(Form targetForm)
{
targetForm.WindowState = FormWindowState.Normal;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.WindowState = FormWindowState.Maximized;
}
public void LeaveFullScreenMode(Form targetForm)
{
targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
targetForm.WindowState = FormWindowState.Normal;
}
}
// System.Globalization.CultureInfo cl2 = new System.Globalization.CultureInfo("en-US");
SpeechRecognitionEngine speechrecog = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
SpeechSynthesizer ss = new SpeechSynthesizer();
PromptBuilder pb = new PromptBuilder();
Choices zlist = new Choices();
Form2 frm = new Form2();
FullScreen fs = new FullScreen();
bool SpeechRecognitionState = true;
Choices dirlist = new Choices();
SpeechRecognitionEngine speechrecog1 = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
bool sprs2 = false;
Choices us = new Choices();
string dir234;
string[] gm;
private void Form11_Load(object sender, EventArgs e)
{
listBox1.Visible = false;
string dir = "C:/Users/" + Environment.UserName + "/Documents/Juliet/response";
DirectoryInfo dinfo = new DirectoryInfo(dir);
FileInfo[] Files = dinfo.GetFiles("*.txt");
webBrowser1.ScriptErrorsSuppressed = true;
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
listBox1.Items.Add(file2.Name.Replace(yts + "", ""));
}
/* String[] list = new String();
list = listBox1.Items.OfType<string>().ToList();
*/
fs.EnterFullScreenMode(this);
textBox1.Width = toolStrip1.Width - 10;
// toolStripTextBox1.Width = toolStrip1.Width - 30;
// toolStripTextBox1.Select();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Teen);
zlist.Add(new string[] { "exit"});
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
dirlist.Add(new string[]{"Mr.Danely"});
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
dirlist.Add(file2.Name.Replace(yts + "", ""));
}
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
try
{
if (SpeechRecognitionState == true)
{
speechrecog.RequestRecognizerUpdate();
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
speechrecog.SpeechRecognized += speechrecog_SpeechRecognized;
speechrecog.SetInputToDefaultAudioDevice();
speechrecog.RecognizeAsync(RecognizeMode.Multiple);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
//us.Add(new string[] { "yes","no","good","bad" });
us.Add(new string[] { "exit" });
Grammar gr12 = new Grammar(new GrammarBuilder(us));
if (sprs2 == true)
{
}
}
void speechrecog1_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if(File.Exists(#"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//"+e.Result.Text.ToString()+".txt"))
{
string hjjk = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//" + e.Result.Text.ToString() + ".txt";
StreamReader file = new StreamReader(hjjk);
string readText = file.ReadLine();
file.Close();
ss.Speak(readText);
timer2.Interval = 10;
timer2.Start();
}
}
void speechrecog_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string igput = e.Result.Text.ToString();
dir234 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//" + igput + ".txt";
if (igput == "exit")
{
speechrecog.RecognizeAsyncStop();
this.Hide();
frm.Closed += (s, args) => this.Close();
frm.Show();
}
else
{
if (File.Exists(dir234))
{
StreamReader file = new StreamReader(dir234);
string readText = file.ReadLine();
file.Close();
if (readText.Contains("%"))
{
string[] words = readText.Split('%');
Random r = new Random();
int selection = r.Next(1, 3);
if (selection == 1)
{
ss.SpeakAsync(words[0]);
}
if (selection == 2)
{
if (readText.Contains('#'))
{
SpeechRecognitionState = false;
us.Add(new string[] { "exit" });
gm = words[1].Split('#');
string speak = words[0] + gm[0];
ss.SpeakAsync(speak);
List<string> lk = gm.ToList();
lk.RemoveAt(0);
string[] hkl = lk.ToArray<string>();
foreach(string g3 in hkl)
{
if (g3.Contains(".txt"))
{
string fj = g3.Replace(".txt" + "", "");
us.Add(fj);
}
else
{
string fj = g3;
us.Add(fj);
}
}
string dir333 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1";
Grammar gr12 = new Grammar(new GrammarBuilder(us));
try
{
speechrecog1.RequestRecognizerUpdate();
speechrecog1.LoadGrammar(gr12);
speechrecog1.SpeechRecognized += speechrecog1_SpeechRecognized;
speechrecog1.SetInputToDefaultAudioDevice();
speechrecog1.RecognizeAsync(RecognizeMode.Single);
//speechrecog1.RecognizeAsyncStop();
//speechrecog.RecognizeAsync(RecognizeMode.Multiple);
//_completed.WaitOne(); // wait until speech recognition is completed
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
// timer2.Interval = 7000;
//timer2.Start();
// timer2.Interval = 5000;
//timer2.Start();
}
else
{
string speak = words[0] + words[1];
ss.SpeakAsync(speak);
}
}
}
else
{
ss.Speak(readText);
}
}
else
{
try
{
tabControl1.SelectedIndex = 1;
webBrowser1.Navigate("https://www.google.com/search?q=" + e.Result.Text.ToString());
}
catch (Exception ex)
{
string ggh = "Error"+ex;
}
}
}
/* SpeechRecognitionState = false;
timer1.Interval = 3000;
timer1.Start();
* */
textBox1.Text = "You: "+e.Result.Text.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
SpeechRecognitionState = true;
timer1.Stop();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void timer2_Tick(object sender, EventArgs e)
{
//loading the grammar again somehow make the recognition better
speechrecog.UnloadAllGrammars();
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
SpeechRecognitionState = true;
speechrecog1.RecognizeAsyncStop();
speechrecog1.UnloadAllGrammars();
timer2.Stop();
}
}
}
For example:
the text file how are you.txt contains:
i am fine. thank you.% how are you#good#bad
and the computer asks if im good and I reply with good. In the good.txt file:
Oh thats cool
the first time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(1 time)
the 2nd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 2 times)
the 3rd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 3 times)
How do i fix the repetition problem.
Thanks to #Nikolay Shmyrev I found the solution. As he said my event handler was firing twice. So inside it I put a:
try
{
//My code
}
finally
{
speechrecog1.SpeechRecognized -= speechrecog1_SpeechRecognized;
}
I'm doing project in C# that read from a video file and convert it to subtitle text, but i want to get the start time for each text line so it can be shown in the video at the right time, i tried the AudioPosition but it not working well, is there a away to do this?
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading.Tasks;
namespace project
{
public partial class Form1 : Form
{
StringBuilder sb = new StringBuilder();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string[] tokens;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "WAV|*.wav";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
Grammar gr = new DictationGrammar();
sre.LoadGrammar(gr);
sre.SetInputToWaveFile(#openFileDialog1.FileName);
while (true)
{
try
{
var recText = sre.Recognize();
sb.Append(recText.Audio.AudioPosition + " * ");
textBox4.Text = sb.ToString();
tokens = sb.ToString().Split('#');
for (int i = 0; i < tokens.Length - 1; i++)
{
textBox2.AppendText(tokens.Length.ToString());
textBox2.AppendText(i+" - "+tokens[i]);
textBox2.AppendText(Environment.NewLine);
}
}
catch (Exception ex)
{
break;
}
}
}
I want to develop a client-server application. I started the project but I encountered the some problems. When I want to connect to server with one client, everything is done. Program is working. But when I want to connect with two or three etc. PC to server, clients of them is working but others is not working. How can I fix this problem?
Here is the my code;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Timers;
using ClientServer;
namespace ClientServer
{
public partial class Form1 : Form
{
private TcpClient Client;
private StreamReader STR;
public StreamWriter STW;
public string receive;
public string text_to_send;
//int zaman;
public Form1()
{
InitializeComponent();
- Client = new TcpClient();
Control.CheckForIllegalCrossThreadCalls = false; //cross threading problem
IPAddress[] LocalIP = Dns.GetHostAddresses(Dns.GetHostName()); // my IP Adress
foreach (IPAddress adress in LocalIP)
{
if(adress.AddressFamily== AddressFamily.InterNetwork)
{
textBox3.Text = adress.ToString();
}
}
}
private void button2_Click(object sender, EventArgs e) //Start server
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
listener.Start();
Client = listener.AcceptTcpClient();
STR = new StreamReader(Client.GetStream());
STW = new StreamWriter(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //receive data background
backgroundWorker2.WorkerSupportsCancellation = true; //ability cancel this thread
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receive data
{
while(Client.Connected)
{
try
{
receive = STR.ReadLine();
if(receive=="soru1")
{
label7.Text = "Merhaba bu bir denemedir :)";
//zaman = 45;
timer1.Enabled = true;
}
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Sen:" + receive + "\n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //veri gönder
{
if(Client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ben:" + text_to_send + "\n"); }));
}
else
{
MessageBox.Show("Gönderim başarısız!");
}
backgroundWorker2.CancelAsync();
}
private void button3_Click(object sender, EventArgs e) //Connect Server
{
Client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));
try
{
Client.Connect(IP_End);
if(Client.Connected)
{
textBox2.AppendText("Server'a bağlantı sağlandı" + "\n");
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //receive data in background
backgroundWorker2.WorkerSupportsCancellation = true; //
}
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
private void button1_Click(object sender, EventArgs e) //Send Button
{
if(textBox1.Text != "")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
//private void timer1_Tick(object sender, System.EventArgs e) //
//{
// zaman--; //timer her saniyede sayıyı 1 azaltacak
// label9.Text = zaman.ToString();
// if (zaman == 0)
// {
// timer1.Enabled = false;
// }
//}
}
}
Here a good links:
http://www.mikeadev.net/2012/07/multi-threaded-tcp-server-in-csharp/
https://www.codeproject.com/Articles/511814/Multi-client-per-one-server-socket-programming-in
tcpListener.Start();
Console.WriteLine("************This is Server program************");
Console.WriteLine("Hoe many clients are going to connect to this server?:");
int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());
for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}
I have a little problem with setting my client-server app for multiple clients usage. I can connect to server and use one client. I modified a little the code to connect via second client, but i don't really know how can i read and send datas to server from second client that are visible also in first client and server. Any ideas/help? Thanks in advance!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Server_WF
{
public partial class Form1 : Form
{
private TcpClient client;
static List<TcpListener> listeners = new List<TcpListener>();
public StreamReader SR;
public StreamWriter SW;
public string otrzymano;
public String msg;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); // Pobieranie własnego IP
foreach(IPAddress adres in localIP)
{
if (adres.AddressFamily == AddressFamily.InterNetwork)
{
textBox3.Text = adres.ToString();
}
}
}
private void button2_Click(object sender, EventArgs e) // START SERVER
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
listeners.Add(listener);
listener.Start();
client = listener.AcceptTcpClient();
SR = new StreamReader(client.GetStream());
SW = new StreamWriter(client.GetStream());
SW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); // Rozpocznij odbieranie danych
backgroundWorker2.WorkerSupportsCancellation = true; // Zdolność do usunięcia wątku
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) // Odbieranie danych
{
while(client.Connected)
{
try
{
otrzymano = SR.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ktoś: " + otrzymano + "\n"); }));
otrzymano = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) // Przesyłanie danych
{
if(client.Connected)
{
SW.WriteLine(msg);
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ja: " + msg + "\n"); }));
}
else
{
MessageBox.Show("Wysyłanie nie powiodło się.");
}
backgroundWorker2.CancelAsync();
}
private void button3_Click(object sender, EventArgs e) // Połącz z serwerem
{
client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));
try
{
client.Connect(IP_End);
if(client.Connected)
{
textBox2.AppendText("Połączono z serwerem..." + "\n");
SW = new StreamWriter(client.GetStream());
SR = new StreamReader(client.GetStream());
SW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); // Rozpocznij odbieranie danych
backgroundWorker2.WorkerSupportsCancellation = true; // Zdolność do usunięcia wątku
}
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text != "")
{
msg = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
}
}
Oh dear, there's a lot to do in your code. First of all: don't call CancelAsync from your background worker code. It is not necessary and probably causes problem. Also, a background worker should never ever display MessageBoxes!
Secondly, a background worker is not the right tool in this case!
Thirdly: You need to make your code completely asynchronous. So please look into the BeginAcceptTcpClient. Then, handle each connected client in its own thread (NOT background worker!).
It's probably best you google for examples on how to do this, as this would be far too much to write up here.