Before i begin I know its messy, I'm getting it working before I clean it up. This is also just for my own knowledge growth I do not intend on rolling this out throughout the company. I have made a monitoring program to check the status of a couple of servers for one of my clients. I have managed to get all the relevant data I need from the ping to the servers, I take the data and send it to the "sort" method where it sends that to the next method which figures out which label I should change the text of, it makes it into these if statements however it just doesn't update the text.
I have already tried:
Application.doEvents();
Label.Refresh();
Label.Update();
I've tried using multithreading too see if that would perhaps force it through.
I have even tried using a button to manually update and that didn't work either.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
Synergy s = new Synergy();
s.Start();
}
private void Label2_Click(object sender, EventArgs e)
{
}
public void Sort(String Name, double P, long RTT, String Response)
{
Console.WriteLine(Name + ": Inside Sort");
if (Name.Contains("SYN-"))
{
SynergySort(Name, P, RTT, Response);
}
}
public void SynergySort(String Name, double P, long RTT, String Response)
{
Console.WriteLine(Name + ": Inside Synergy Sort");
if (Name.Equals("SYN-DC01"))
{
Console.WriteLine(Name + ": Inside DC01 SORT");
this.SD1R.Text = RTT.ToString();
this.SD1P.Text = P.ToString();
}
else if (Name.Equals("SYN-DC03"))
{
Console.WriteLine(Name + ": Inside DC03 SORT");
this.SD3R.Text = RTT.ToString();
this.SD3P.Text = P.ToString();
}
}
}
public class Synergy
{
private Form1 f = new Form1();
private Pinger ping = new Pinger();
public void Start()
{
NAS01Scan();
DC03Scan();
TRACKERScan();
DC01Scan();
VoiceScan();
NETAPPScan();
}
public void NAS01Scan()
{
Console.WriteLine("Pinging NAS01");
ping.IP("172.16.xx.xxx", 5, "SYN-NAS01");
}
public void DC03Scan()
{
Console.WriteLine("pinging DC03");
ping.IP("172.16.xx.xxx", 5, "SYN-DC03");
}
public void TRACKERScan()
{
Console.WriteLine("pinging TRACKER");
ping.IP("172.16.xx.xxx", 5, "SYN-TRACKER");
}
public void DC01Scan()
{
Console.WriteLine("pinging DC01");
ping.IP("172.16.xx.xxx", 5, "SYN-DC01");
}
public void NETAPPScan()
{
Console.WriteLine("pinging NETAPP");
ping.IP("172.16.xx.xxx", 5, "SYN-NETAPP");
}
public void VoiceScan()
{
Console.WriteLine("pinging AVAYA_Voice");
ping.IP("172.16.xx.xxx", 5, "SYN-AVAYA_Voice");
}
}
public class Pinger
{
private Form1 f = new Form1();
public void IP(String host, int echoNum, String Name)
{
long totalTime = 0;
PingReply reply = null;
int timeout = 120;
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int failed = 0;
for (int i = 0; i < echoNum; i++)
{
reply = pingSender.Send(host, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
}
else
{
failed += 1;
Console.WriteLine(Name + ": " + reply.Status);
}
}
totalTime += reply.RoundtripTime;
Console.WriteLine(Name + ": RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine(Name + ": Time in MS = " + totalTime / echoNum);
double percent = (failed / echoNum) * 100;
Console.WriteLine(Name + ": Percent Loss is " + percent);
f.Sort(Name, percent, reply.RoundtripTime, reply.Status.ToString());
}
}
Related
Using visual studios Windows forms on c#, I'm making a chatprogram with unlimited clients and one server. The server has to be activated before I connect any client. However, after connecting one or more clients and closing one of them, the server crashes. I can nor close it or send any data from my clients to it without getting an error. The CPU usage of my computer rises to 50% during the crash. After I manage to close the server through task manager, different code lines are highlighted, indicating the error.
Here's my server code:
namespace TCPa
{ // skapar en lista med tcp clients
// säg till så att send funktioner tar tcp clients som input i
metoderna och referera till metoderna
// och loopa genom listan, som kallar metoden i lista.
public partial class Server : Form
{
TcpClient klient = null;
List<TcpClient> klientLista = new List<TcpClient>();
TcpListener lyssnare;
int port = 0;
public Server()
{
InitializeComponent();
}
private void btnTaEmot_Click(object sender, EventArgs e)
{
try
{
port = int.Parse(tbxPort.Text);
if (port >= 1024 && port <= 65535)
{
les(port);
}
else
{
MessageBox.Show("Skriv in ett giltigt portnummer mellan 1024 och 65535");
}
}
catch (Exception)
{
MessageBox.Show("Skriv in ett giltigt portnummer mellan 1024 och 65535");
}
}
public void les(int portT)
{
btnTaEmot.Enabled = false;
tbxPort.Enabled = false;
try
{
lyssnare = new TcpListener(IPAddress.Any, portT);
lyssnare.Start();
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
StartAccepting();
}
public async void StartAccepting()
{
try
{
klient = await lyssnare.AcceptTcpClientAsync();
klientLista.Add(klient);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
StartReading(klient);
StartAccepting();
}
public async void StartReading(TcpClient k)
{
byte[] buffer = new byte[1024];
int n = 0;
try
{
///NEW
n = await k.GetStream().ReadAsync(buffer, 0, 1024);
if (n <= 0)
{
klient.Close();
}
////NEW
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
StartSending(k, Encoding.Unicode.GetString(buffer, 0, n));
tbxLogg.AppendText(Encoding.Unicode.GetString(buffer, 0, n));
StartReading(k);
}
public async void StartSending(TcpClient klientSomSkickar, string message)
{
if (klientLista.Count > 0)
{
byte[] utData = Encoding.Unicode.GetBytes(message);
foreach (TcpClient klient in klientLista)
{
try
{
if (klient != klientSomSkickar)
{
await klient.GetStream().WriteAsync(utData, 0, utData.Length);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text); return;
}
}
}
}
private void Server_FormClosing(object sender, FormClosingEventArgs e)
{
lyssnare.Stop();
if (klient != null && klient.Connected)
{
klient.Close();
}
}
}
}
Here's my client code
namespace Klient
{
public partial class Klient : Form
{
TcpClient klient = new TcpClient();
public Klient()
{
InitializeComponent();
btnSend.Enabled = false;
}
private void btnAnslut_Click(object sender, EventArgs e)
{
Connect();
}
private async void Connect()
{
IPAddress adress = IPAddress.Parse(tbxIP.Text);
int port = int.Parse(tbxPort.Text);
try
{
await klient.ConnectAsync(adress, port);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
if (klient.Connected)
{
btnAnslut.Enabled = false;
btnSend.Enabled = true;
tbxNmn.Enabled = false;
tbxMedd.Focus();
}
StartReading(klient);
}
private async void btnSend_Click(object sender, EventArgs e)
{
if (klient.Connected)
{
string namn = tbxNmn.Text;
string tid = DateTime.Now.ToString("HH:mm tt");
if (String.IsNullOrEmpty(tbxMedd.Text) || String.IsNullOrWhiteSpace(tbxMedd.Text))
{
MessageBox.Show("Skriv in ditt meddelande");
}
else
{
byte[] utData = Encoding.Unicode.GetBytes("<" + " " + namn + " " + ">" + " " + tid + ":" + "\t" + tbxMedd.Text + "\r\n");
try
{
tbxLogg.AppendText("<" + " " + namn + " " + ">" + " " + tid + ":" + "\t" + tbxMedd.Text + "\r\n");
await klient.GetStream().WriteAsync(utData, 0, utData.Length);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
}
}
tbxMedd.Clear();
}
public async void StartReading(TcpClient k)
{
byte[] buffer = new byte[1024];
int n = 0;
try
{
n = await k.GetStream().ReadAsync(buffer, 0, 1024);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
tbxLogg.AppendText(Encoding.Unicode.GetString(buffer, 0, n));
StartReading(k);
}
private void Klient_FormClosing(object sender, FormClosingEventArgs e)
{
if (klient != null)
klient.Close();
}
}
}
Any help is appreciated!!
I have a communication device which sends requests every two seconds through COM. Between the requests, the device waits for response. I'm building software in C# with SerialPort. I call an event handler for data receiving and I run a method in new thread with while loop which checks that the request is as expected and calls method responsible for response. The thing is, after response next received data is wrong. Here is the code:
The SerialPortManager:
class SerialPortManager : IDisposable
{
...
public void connect()
{
if (mSerialPort.IsOpen)
return;
mSerialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
try
{
mSerialPort.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
mStatus = Status.DISCONNECTED;
return;
}
if (mSerialPort.IsOpen)
{
mStatus = Status.CONNECTED;
Thread tryToResponseThread = new Thread(tryToResponse);
tryToResponseThread.Start();
}
}
private void tryToResponse()
{
while (mStatus == Status.CONNECTED)
{
if (mRequest.Length >= 56)
{
string checksum = "555555555555555580808080";
if (mRequest.Length > 56)
{
mRequest.Remove(55, mRequest.Length - 56);
Debug.Print("cutting");
}
if (mRequest.ToString().StartsWith(checksum))
{
StringBuilder strToCMD = new StringBuilder();
for (int i = 0; i < mRequest.Length; i += 2)
{
strToCMD.Append(mRequest[i]);
strToCMD.Append(mRequest[i + 1]);
strToCMD.Append(" ");
}
StringBuilder address = new StringBuilder();
StringBuilder group = new StringBuilder();
address.Append(mRequest.ToString(24, 8));
group.Append(mRequest.ToString(24 + 8, 2));
mMainForm.appendCMDTextboxText(Environment.NewLine);
mMainForm.appendCMDTextboxText(DateTime.Now.ToLongTimeString() + " [RX] " + address.ToString() + " " + group.ToString() + "\t");
mMainForm.appendCMDTextboxText(strToCMD.ToString());
byte[] request = ByteArrayConverter.fromString16(mRequest.ToString());
mRequest.Clear();
response(request);
Array.Clear(request, 0, request.Length);
Debug.Print("starts with checksum");
}
else if (mRequest.ToString().Contains(checksum))
{
int indexOfChecksum = mRequest.ToString().IndexOf(checksum);
mRequest.Remove(0, indexOfChecksum);
Debug.Print("contains");
}
else
{
int index = 0;
bool found = false;
for (int i = 0; i < checksum.Length; i++)
{
StringBuilder s = new StringBuilder();
int sub = mRequest.Length - checksum.Length + i + 2;
if (sub == mRequest.Length)
break;
s.Append(mRequest.ToString().Substring((Math.Max(0, mRequest.Length - checksum.Length + i + 2))));
s.Append(mRequest.ToString(0, i + 2));
if (s.ToString().Equals(checksum))
{
index = sub;
found = true;
break;
}
}
if (found)
{
mRequest.Remove(0, index);
}
else
{
mRequest.Clear();
}
Debug.Print("on start and end");
}
}
}
}
private void response(byte[] request)
{
Luminaire lumToResponse = mLuminaireManager.getLuminaire(request);
if (lumToResponse == null)
{
return;
}
else
{
if (lumToResponse.isNotResponding())
return;
}
byte[] responseMsg = lumToResponse.getWholeFrame(request);
mMainForm.setCommandLabelForResponsingLuminaire(lumToResponse);
mMainForm.appendCMDTextboxText(Environment.NewLine + DateTime.Now.ToLongTimeString() + " [TX]\t");
string responseMsgAsString = ByteArrayConverter.toString(responseMsg).Replace("-", " ");
mMainForm.appendCMDTextboxText(responseMsgAsString);
write(responseMsg, 0, responseMsg.Length);
mSerialDataEventArgs.clearData();
}
public void write(byte[] buffer, int offset, int count)
{
if (mStatus == Status.DISCONNECTED || mSerialPort.IsOpen == false)
{
mStatus = Status.DISCONNECTED;
return;
}
mSerialPort.Write(buffer, offset, count);
}
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (mStatus == Status.DISCONNECTED)
return;
int dataLength = mSerialPort.BytesToRead;
if (dataLength == 0)
return;
byte[] data = new byte[dataLength];
mSerialPort.Read(data, 0, dataLength);
mSerialDataEventArgs.setData(data);
mDataReceived?.Invoke(this, mSerialDataEventArgs);
}
...
}
The helpser class for passing the received data:
public class SerialDataEventArgs : EventArgs
{
public SerialDataEventArgs()
{
}
public void setData(byte[] data)
{
clearData();
mData = data;
}
public SerialDataEventArgs(byte[] dataInByteArray)
{
mData = dataInByteArray;
}
public void clearData()
{
if (mData == null)
return;
Array.Clear(mData, 0, mData.Length);
}
public byte[] mData;
}
And the main class:
public partial class MainForm : Form
{
...
private void MainForm_Load(object sender, EventArgs e)
{
mSerialPortManager = new SerialPortManager();
mSerialPortManager.setPortBoudRate((int)numUpDown_SerialPortSpeed.Value);
mLuminaireManager = new LuminaireManager();
mSerialPortManager.mMainForm = this;
mSerialPortManager.mLuminaireManager = mLuminaireManager;
fixTableLayoutColumnSize(ref tl_SingleLuminaire);
fillTheRestOfSingleLuminaireGroupBoxes();
fillSerialPortComboBoxWithNamesOfAvailablePorts();
mSerialPortManager.mDataReceived += new EventHandler<SerialDataEventArgs>(serialPortManager_DataReceived);
mIsPaused = false;
}
private void serialPortManager_DataReceived(object sender, SerialDataEventArgs e)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new EventHandler<SerialDataEventArgs>(serialPortManager_DataReceived), new object[] { sender, e });
return;
}
if (mIsPaused)
return;
mSerialPortManager.mRequest.Append(ByteArrayConverter.toString(e.mData).Replace("-", ""));
}
...
}
The communication should be like below:
request: 5555555555555555808080800100000001001A0006070001060031B1
response: 55555555555555558080808001000000010000808076
request: 5555555555555555808080800200000001001A0006070001060034B2
response: 555555555555555580808080020000000100008041BA
request: 5555555555555555808080800300000001001A000607000106003473
response: 55555555555555558080808003000000010000804049
And so on. It is just example, what the request frame should look like. As you can see, the device asks for 1,2,3,4, etc. It always asks in this order. The last four values are just checksum. What I receive after response is like:
request: 5555555555555555808080800200000001001A0006070001060034B2
response: 555555555555555580808080020000000100008041BA
request: 55555555555555558080808002000000000A0100000000000000BCAE
After response for 2, there should be an ask for 3. If I set the software to not responding, every request looks fine.
What I am doing wrong?
Ok, so everything is okay. My COM interface is broken :( Everything is fine with both ways - DataReceived event handler and read() right after write() (no matter which solution is better in programming way). Thank you all for trying help with my case anyway!
I have a problem that I can't resolve by myself.
I have an ObservableCollection of "product" with a "price" property.
Every second, the price of every products change. This is my server part.
I have a window, with some textbox, which bind on the price property.
In an other part, I have a client. The client needs to get the price of all products.
So, first, my client connect to my server (no problem here). it sends a message to server, server receives it.
My problem is here : the value of the price property change every second, but in my thread, I can't get the new values...
Here my code :
- Product :
private volatile float price;
public float Price
{
get { return price; }
set
{
price = value;
notifyPropertyChanged("Price");
}
}
public Product(int time)
{
timer = new Timer(time);
timer.Elapsed += timer_Elapsed;
timer.Start();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
this.Price++;
}
my server :
private ObservableCollection<product> listGroupProduct;
public MainWindow()
{
Thread thread;
InitializeComponent();
this.DataContext = this;
// Create the server
thread = new Thread(() => createServer(ref listGroupProduct));
thread.Start();
}
public static void createServer(ref ObservableCollection<Product> list)
{
string client = "";
try
{
IPAddress ipAdress = IPAddress.Parse("192.168.1.50");
TcpListener listener = new TcpListener(ipAdress, 1220);
listener.Start();
socket = listener.AcceptSocket();
// Receive client name
client = ReceiveMessage(100);
MessageBox.Show("New client connected : " + client);
// Send number of products
SendMessage(list.Count.ToString());
// Get articles request from a client
ReceiveMessage(8);
// Send all articles
while (true)
{
for (int i = 0; i < 3; i++)
{
if (articlesString != "")
articlesString += "|";
articlesString += list[i].Price + ";";
}
byte[] bytes = new byte[list.Count * 50];
bytes = System.Text.Encoding.ASCII.GetBytes(articlesString.ToCharArray());
socket.Send(bytes);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private static void SendMessage(string p)
{
byte[] bytes = new byte[p.Length];
bytes = System.Text.Encoding.ASCII.GetBytes(p.ToCharArray());
socket.Send(bytes);
}
private static string ReceiveMessage(int p)
{
string tmp = "";
byte[] b = new byte[p];
int k = socket.Receive(b);
for (int i = 0; i < k; i++)
tmp += Convert.ToChar(b[i]);
return tmp;
}
My client :
private StreamSocket streamSocket;
public string Server = "192.168.1.89";
public int Port = 1220;
IInputStream inputStream;
IOutputStream outputStream;
public MainPage()
{
this.InitializeComponent();
CreateSocket();
}
void timer_Tick(object sender, object e)
{
SendMessage("articles");
toto.Text = "Message send : articles";
GetAllArticles();
}
private async void GetAllArticles()
{
toto.Text = await GetMessage(50);
toto.Text = "Waiting articles...";
toto.Text = await GetMessage(articlesNumber * 50));
}
private async Task CreateConnection()
{
SendMessage("tablet");
toto.Text = "message send : tablet";
articlesNumber = int.Parse(await GetMessage(1));
toto.Text = "Number articles : " + articlesNumber.ToString();
}
private async void CreateSocket()
{
DispatcherTimer timer = new DispatcherTimer();
streamSocket = new StreamSocket();
await streamSocket.ConnectAsync(new HostName(Server), Port.ToString());
inputStream = streamSocket.InputStream;
outputStream = streamSocket.OutputStream;
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += timer_Tick;
// Envoi du nom et réception du nombre d'articles
await CreateConnection();
// Réception de tous les articles chaque secondes
SendMessage("tablet");
timer.Start();
}
private async void SendMessage(string message)
{
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);
await outputStream.WriteAsync(buffer);
}
private async Task<string> GetMessage(int size)
{
byte[] tmp = new byte[size];
IBuffer buffer1 = CryptographicBuffer.CreateFromByteArray(tmp);
toto.Text = "Waiting message... (size : " + size.ToString() + ")";
await inputStream.ReadAsync(buffer1, (uint)size, InputStreamOptions.None);
toto.Text = "Message received !";
return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffer1);
}
(By the way : "toto" is a textbox I use for debug :) )
Have you an idea why my client receive well the first value, but when, on my server side, the value change, my client continue to get the same value and not the new one ?
It looks like the server has infinite loop and keeps resending same data over and over again. CreateServer has the infinite loop immediately after the "Send all articles" comment.
I am working on this GUI for serial port application. I recently added stop and wait protocols to the application. Surprisingly my disconnect button stopped working. I have thought through the logic and I have not been able to find the problem.
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public bool packetreceived = false;
private SerialPort sp = null; //<---- serial port at form level
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
//delegate variable to disconnect
public AddDataDelegate disconnectDelegate = null;
public void AddDataMethod(String myString)
{
richTextBox1.AppendText(myString);
}
/**
* Takes byte array and returns a string representation
*
*/
public String parseUARTData(byte[] data)
{
if (data.Length == 11)
{
String rv = "";
DataFields d = new DataFields();
if (!packetreceived)
{
d = mainLogic.parseData(data);
packetreceived = true;
}
//TODO
System.Threading.Thread.Sleep(5000);
if (d.sequence == 0)
{
sp.Write("1\r\n");
}
else
{
sp.Write("0\r\n");
}
packetreceived = false;
//now display it as a string
rv += STR_OPCODE + " = " + d.opcode + "\n";
rv += STR_CRC + " = " + d.crc + "\n";
rv += STR_SEQ + " = " + d.sequence + "\n";
rv += STR_FLAGS + " = " + d.flags + "\n";
rv += STR_TEMP + " = " + d.temperature + "\n";
rv += STR_HUMID + " = " + d.humidity + "\n";
rv += STR_PH + " = " + d.ph + "\n";
return rv + "\n\n";
}
else
{
return Encoding.ASCII.GetString(data);
}
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s = sp.ReadExisting();
if (disconnectDelegate != null)
{
disconnectDelegate.Invoke(s);
}
richTextBox1.Invoke(this.myDelegate, new Object[] { parseUARTData(Encoding.ASCII.GetBytes(s)) });
}
private void button1_Click(object sender, EventArgs e)
{
connect.Enabled = false;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (!sp.IsOpen)
{
//sp.PortName = this.comboBox1.SelectedItem.ToString();
sp.Open();
}
// send data to port
sp.Write("####,###########\r\n");
disconnect.Enabled = true;
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
connect.Enabled = true;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (sp.IsOpen)
{
// send data to port
sp.Write("+++\r\n");
//add the delegate
disconnectDelegate = new AddDataDelegate(onDisconnect);
//sp.WriteTimeout = 500;
// sp.Write("####,0\r\n");
}
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
finally
{
disconnect.Enabled = false;
}
}
public void OnApplicationExit(object sender, EventArgs e)
{
sp.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//foreach (string port in ports)
//{
// comboBoxSerialPorts.Items.Add(port);
//}
}
private void onDisconnect(string msg)
{
string trimmedMsg = msg.Trim();
if (trimmedMsg.Equals("OK"))
{
//send the second time
sp.Write("##,0\r\n");
//null the object
disconnectDelegate = null;
}
}
private void comPort_Click(object sender, EventArgs e)
{
try
{
if (sp.IsOpen)
{
//send data to port
sp.Write("1\r\n");
MessageBox.Show("bluetooth is transmitting data...");
//message box telling user that you are asking for data.
}
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}
I want my application will show on my form my class properties so I started my class with BackgroundWorker and create ProgressChanged.
my class:
public class DumpFile
{
PacketDevice _device;
public int _packetsCount;
public double _bitsPerSecond;
public double _packetsPerSecond;
public DateTime _lastTimestamp;
public delegate void dlgPackProgress(int progress);
public event dlgPackProgress evePacketProgress;
public DumpFile(PacketDevice device, string pcapPath)
{
_device = device;
_pcapPath = pcapPath;
_packetsCount = 1;
}
public void startCapturing()
{
OnPacketProgress(_packetsCount++);
using (PacketCommunicator communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the device
{
ThreadStart starter = delegate { openAdapterForStatistics(_device); };
new Thread(starter).Start();
using (PacketDumpFile dumpFile = communicator.OpenDump(_pcapPath)) //open the dump file
{
communicator.ReceivePackets(0, dumpFile.Dump); //start the capture
}
}
}
private void OnPacketProgress(int packet)
{
var handler = evePacketProgress;
if (handler != null)
{
handler(packet);
}
}
public void openAdapterForStatistics(PacketDevice selectedOutputDevice)
{
using (PacketCommunicator statCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the output adapter
{
ThreadStart start = delegate { test(selectedOutputDevice); };
new Thread(start).Start();
statCommunicator.SetFilter("tcp"); //compile and set the filter
statCommunicator.Mode = PacketCommunicatorMode.Statistics; //put the interface in statstics mode
statCommunicator.ReceiveStatistics(0, StatisticsHandler);
}
}
public void test(PacketDevice selectedOutputDevice)
{
using (PacketCommunicator communicator = selectedOutputDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
communicator.ReceivePackets(0, PacketHandler);
}
}
private void PacketHandler(Packet packet)
{
string result = _packetsCount.ToString() + ". " + packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length;
_packetsCount++;
}
private void StatisticsHandler(PacketSampleStatistics statistics)
{
DateTime currentTimestamp = statistics.Timestamp; //current sample time
DateTime previousTimestamp = _lastTimestamp; //previous sample time
_lastTimestamp = currentTimestamp; //set _lastTimestamp for the next iteration
if (previousTimestamp == DateTime.MinValue) //if there wasn't a previous sample than skip this iteration (it's the first iteration)
{
return;
}
double delayInSeconds = (currentTimestamp - previousTimestamp).TotalSeconds; //calculate the delay from the last sample
_bitsPerSecond = statistics.AcceptedBytes * 8 / delayInSeconds; //calculate bits per second
_packetsPerSecond = statistics.AcceptedPackets / delayInSeconds; //calculate packets per second
}
}
start button who start capturing:
private void btnStartCapture_Click(object sender, EventArgs e)
{
timerSniffer.Start();
btnStartTabSniffer.Enabled = false;
btnStopTabSniffer.Enabled = true;
groupBoxSelectTabSniffer.Enabled = false;
bgWorker = new BackgroundWorker();
bgWorker.WorkerReportsProgress = true;
bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWSniffer_ProgressChanged);
bgWorker.DoWork += new DoWorkEventHandler(
(s3, e3) =>
{
DumpFile dumpFile = new DumpFile(deviceForCapturing, pcapFilePathSniffer);
tshark.evePacketProgress += new DumpFile.dlgPackProgress(
(packet) =>
{
bgWorker.ReportProgress(packet, dumpFile);
});
dumpFile.startCapturing();
});
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s3, e3) =>
{
groupBoxSelectTabSniffer.Enabled = true;
});
bgWorker.RunWorkerAsync();
}
ProgressChanged:
private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var dumpFile = (DumpFile)e.UserState;
lblNumberOfPacketsTabSniffer2.Text = dumpFile._packetsCount.ToString("#,##0");
lblTrafficRateTabSniffer2.Text = (dumpFile._bitsPerSecond * 0.000001).ToString("0.##") + " Mbit/sec" + " (" + dumpFile._bitsPerSecond.ToString("#,##0") + " Bits/sec" + ")";
lblPacketsRateTabSniffer2.Text = dumpFile._packetsPerSecond.ToString("#,##0") + " Packets/sec";
}
the problem is that my application "get into" ProgressChanged functions but only in one time.
I think I missed something in my class.
I can only find one call to OnPacketProgress(), and it's outside of any loop.
public void startCapturing()
{
OnPacketProgress(_packetsCount++);
....
}
So Yes, that will only be called once.
You need something inside ReceivePackets()