any help much appreciated!
I have a UDP listener which has button controls to start/stop the UDP, and write to .txt file, however the latter part does not work as I wish.
The beginInvoke sends the 'data' to thread [button_start_writing_Click] causing it to trigger itself, rather than when I click the button.
How would I like it so the data is continually received in the textbox, then I choose the moment to start logging to txt file?
Many thanks in advance!
public partial class Form1 : Form
{
private UdpClient Client;
public Form1()
{
InitializeComponent();
}
private void button_start_Click(object sender, EventArgs e)
{
Client = new UdpClient(Convert.ToInt32(textBox_port.Text));
Client.BeginReceive(DataReceived, null);
button_stop.Click += Button_stop_Click;
}
private void DataReceived(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, Convert.ToInt32(textBox_port.Text));
byte[] data;
try
{
data = Client.EndReceive(ar, ref ip);
if (data.Length == 0)
return; // No more to receive
Client.BeginReceive(DataReceived, null);
}
catch //(ObjectDisposedException)
{
return; // Connection closed
}
// Send the data to the UI thread
this.BeginInvoke((Action<IPEndPoint, string>)DataReceivedUI, ip, Encoding.UTF8.GetString(data));
// Send the data to the writer thread
this.BeginInvoke((Action<IPEndPoint, string>)button_start_writing_Click, ip, Encoding.UTF8.GetString(data));
private void button_start_writing_Click(object sender, EventArgs e)
{
string logfilePath = "C:\\Users\\I4T\\Desktop\\Test Output\\";
File.AppendAllText(logfilePath + "logtest.txt", "[" + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss.fff") + "] " + data);
}