C# Sending UDP packages - c#

I was wondering, is their any way of checking if your program is sending UDP packages to the desired IP?I am a beginner socket programmer. So if you do decide to help me, please explain with some amount of detail. I am only 15 and have been learning c# for only 2 months.
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.Net;
using System.Net.Sockets;
namespace Challenger
{
public partial class Form1 : Form
{
int ipWidth;
String x;
String methodValue;
int threadNumber;
IPEndPoint endPoint;
byte[] buffer;
public Form1()
{
InitializeComponent();
urlTextbox.Text ="www.";
this.MessageTextBox.Size = new System.Drawing.Size(231, 40);
MessageTextBox.Text = "When harpoons, air strikes, and nukes fail.";
threadValue();
methodSetter();
ipLabelText();
}
private void Form1_Load(object sender, EventArgs e)
{
this.BackColor = Color.FromArgb(0, 47, 80); //Dark blue background
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
System.Net.IPAddress[] addressess = System.Net.Dns.GetHostAddresses(urlTextbox.Text);
String ipTextLength = Convert.ToString(addressess[0]);
SendUDPPacket(ipTextLength, 80, "Hello!", 100000000);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Color pixelColor;//Initialize pixelColor
SolidBrush pixelBrush = new SolidBrush(Color.FromArgb(0, 83, 146)); //RGB Brush
e.Graphics.FillRectangle(pixelBrush, 0, 0, 500, 400); //Light blue rectangle for displaying IP address
}
private void urlTextbox_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
System.Net.IPAddress[] addresses = System.Net.Dns.GetHostAddresses(urlTextbox.Text);
String ipTextLength = Convert.ToString(addresses[0]);
label2.Text = Convert.ToString(addresses[0]); //Puts ip into a string-> Label for Display
label2.Location = new Point(80, 20);
}
public void ipLabelText()
{
label2.Parent = panel1;
label2.BackColor = Color.Transparent;
label2.ForeColor = Color.White;
}
private void label2_Click(object sender, EventArgs e)
{
}
private void TimeoutLabel_Click(object sender, EventArgs e)
{
}
private void portLabel_Click(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
this.MessageTextBox.Size = new System.Drawing.Size(231, 40);
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void methodClick(object sender, MouseEventArgs e)
{
}
public void methodSetter()
{
comboBox1.SelectedIndex = 0;
if (comboBox1.SelectedIndex == 0)
{
methodValue = "TCP";
}
if (comboBox1.SelectedIndex == 1)
{
methodValue = "UDP";
}
if (comboBox1.SelectedIndex == 2)
{
methodValue = "HTTP";
}
}
private void textBox3_TextChanged_1(object sender, EventArgs e)
{
}
public void threadValue()
{
textBox3.Text = "10";//Default thread value
threadNumber = Convert.ToInt32(threadNumber);
}
private void ipLockOn_Click(object sender, EventArgs e)
{
IPHostEntry hostEntry;
hostEntry = Dns.GetHostEntry(ip1.Text+"."+ip2.Text+"."+ip3.Text+"."+ip4.Text);
String x = Convert.ToString(hostEntry.AddressList);
label2.Text = x; //Puts ip into a string-> Label for Display
label2.Location = new Point(80, 20);
}
public void SendUDPPacket(string hostNameOrAddress, int destinationPort, string data, int count)
{
// Validate the destination port number
if (destinationPort < 1 || destinationPort > 65535)
throw new ArgumentOutOfRangeException("destinationPort", "Parameter destinationPort must be between 1 and 65,535.");
// Resolve the host name to an IP Address
IPAddress[] ipAddresses = Dns.GetHostAddresses(urlTextbox.Text);
if (ipAddresses.Length == 0)
throw new ArgumentException("Host name or address could not be resolved.", "hostNameOrAddress");
// Use the first IP Address in the list
IPAddress destination = ipAddresses[0];
IPEndPoint endPoint = new IPEndPoint(destination, destinationPort);
byte[] buffer = Encoding.ASCII.GetBytes(data);
// Send the packets
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
while (true)
{
socket.SendTo(buffer, endPoint);
}
}
}
}
Porting LOIC Android Application in C#

https://www.wireshark.org/ - this is the best tool ever for network debugging. You can filter by UDP & port, and it'll give you a detailed breakdown of all the packets & headers, including source & destination IP.

Related

C# Windows Forms Serial Communication with GMap app crash

I've written desktop application, that receives location via serial communication from NRF/GPS module, split that data in order to distinguish latitude, longitude and then i load these coordinates to map(i use GMap). But when i receive data, first 1 or 2 seconds it comes in a little confused form(like this 06840.370056;49.84006068). And i thought adding some Thread.Sleep will solve this problem, but instead application crashes after 5-10 seconds. How can i solve this problem, because i want my app run smoothly? Here is part of my code:
public partial class Form1 : Form
{
public string dataIn;
private List<PointLatLng> _points;
public Form1()
{
_points = new List<PointLatLng>();
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GMapProviders.GoogleMap.ApiKey = AppConfig.Key;
string[] ports = SerialPort.GetPortNames();
cBoxCom.Items.AddRange(ports);
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
gMap.MapProvider = GMapProviders.GoogleMap;
gMap.ShowCenter = false;
gMap.DragButton = MouseButtons.Left;
gMap.SetPositionByKeywords("Chennai, India");
}
private void btnConnect_Click(object sender, EventArgs e)
{
serialPort1.PortName = cBoxCom.Text;
serialPort1.BaudRate = Convert.ToInt32(cBoxBaudrate.Text);
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
serialPort1.Open();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
}
}
private void btnClearDataIn_Click(object sender, EventArgs e)
{
if (richBoxReciever.Text != "")
{
richBoxReciever.Text = " ";
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
dataIn = serialPort1.ReadExisting();
this.Invoke(new EventHandler(ShowData));
}
private void ShowData(object sender, EventArgs e)
{
Thread.Sleep(3000);
richBoxReciever.Text += dataIn;
Thread.Sleep(5000);
string[] locationData = dataIn.Split(new char[] { ';' });
List<string> tokens = new List<string>();
foreach (string s in locationData)
{
if (s.Length != 0)
{
tokens.Add(s);
}
}
txtLat.Text = tokens[0];
txtLon.Text = tokens[1];
}

Return values from serial data received to another function

I am taking serial data from a distance sensor through Arduino to Visual Studio and I have another machine that is controlled by another controller.
Return values from serial data received to another function.
My question is: how to return the values from the function?
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
to a while loop inside the function
private void btnMove_Click(object sender, EventArgs e)
My code is as follows:
using System;
using System.Windows.Forms;
using PokeysLibSR;
using System.Drawing;
using System.Diagnostics;
using System.Threading;
using System.IO.Ports;
using System.Text.RegularExpressions;
namespace Melexis
{
public partial class Form1 : Form
{
PokeysLib pokeys;
public Form1()
{
InitializeComponent();
serialPort1.BaudRate = 9600;
serialPort1.PortName = "COM3";
}
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Open();
}
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string line = serialPort1.ReadLine();
string yourPortStringFormatted = Regex.Replace(line, #"\t|\n|\r", "");
string yourPortStringFormatted1 = yourPortStringFormatted.Trim();
double portNum = Double.Parse(yourPortStringFormatted1);
string line1 = Convert.ToString(portNum / 100);
this.BeginInvoke(new LineReceivedEvent(LineReceived), line1);
}
catch { }
finally
{
GC.Collect();
}
}
private delegate void LineReceivedEvent(string line1);
private void LineReceived(string line1)
{
textBox1.Text = line1;
}
private void btnMove_Click(object sender, EventArgs e)
{
double[] coords = new double[4] { 0, 0, 0, 0 };
byte axisMask = 0;
if (double.TryParse(tbX.Text, out coords[0])) axisMask = (byte)(axisMask + 1);
if (double.TryParse(tbY.Text, out coords[1])) axisMask = (byte)(axisMask + 2);
if (double.TryParse(tbZ.Text, out coords[2])) axisMask = (byte)(axisMask + 4);
while (true)
{
pokeys.StartMove(false, rbAbsolut.Checked, 1, coords);
Thread.Sleep(5000);
coords[0] = -coords[0];
pokeys.StartMove(false, rbAbsolut.Checked, 4, coords);
coords[2] = coords[2] + 10;
Thread.Sleep(5000);
}
}
}

C# how to fix this

I have a error that I don't no how to fix. I would perfer the answer in code. This is the error, Error 1 No overload for
'turnToVideoToolStripMenuItem_Click' matches delegate 'System.EventHandler'
C:\Users\kinoa\documents\visual studio 2013\Projects\Armored Animation Studio\Armored Animation Studio\main.Designer.cs 259 56 Armored Animation Studio.
This is the 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.Tasks;
using System.Windows.Forms;
using NReco.VideoConverter;
using System.Diagnostics;
using System.IO;
namespace Armored_Animation_Studio
{
public partial class main : Form
{
public Point current = new Point();
public Point old = new Point();
public Graphics g;
public Pen p = new Pen(Color.Black, 5);
public List<Image> Animation = new List<Image>();
public main()
{
InitializeComponent();
g = panel1.CreateGraphics();
p.SetLineCap(System.Drawing.Drawing2D.LineCap.Round,
System.Drawing.Drawing2D.LineCap.Round,
System.Drawing.Drawing2D.DashCap.Round);
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
current = e.Location;
g.DrawLine(p, current, old);
old = current;
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
old = e.Location;
if(radioButton1.Checked)
{
p.Width = 1;
}
else if(radioButton2.Checked)
{
p.Width = 5;
}
else if (radioButton3.Checked)
{
p.Width = 10;
}
else if (radioButton4.Checked)
{
p.Width = 15;
}
else if (radioButton5.Checked)
{
p.Width = 30;
}
}
private void button1_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
p.Color = cd.Color;
}
private void button3_Click(object sender, EventArgs e)
{
panel1.Invalidate();
}
private void radioButton7_CheckedChanged(object sender, EventArgs e)
{
p.Color = System.Drawing.Color.White;
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, panel1.Width,
panel1.Height));
Animation.Add(bmp);
}
private void turnToVideoToolStripMenuItem_Click(object sender, EventArgs
e, string [] args)
{
Process proc = new Process();
proc.StartInfo.FileName = "ffmpeg";
proc.StartInfo.Arguments = "-i " + args[0] + " " + args[1];
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
if (!proc.Start())
{
Console.WriteLine("Error starting");
return;
}
StreamReader reader = proc.StandardError;
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine("ffmpeg -i <imagefile> -vcodec mpeg4 out_movie");
}
proc.Close();
}
}
}
Thank you!
Change the method signature:
private void turnToVideoToolStripMenuItem_Click(object sender, EventArgs e, string [] args)
to:
private void turnToVideoToolStripMenuItem_Click(object sender, EventArgs e)
Would take care of the compiler error, but you are left with getting to the data that you expected to be in args. What are you expecting to be passed in that last parameter?

Receiving data from serial port in windows form application

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.Ports;
namespace WindowsFormsApp7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getavaialbleports();
}
void getavaialbleports()
{
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
textBox2.Text = "Please select port settings";
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
button1.Enabled = false;
}
}
catch(UnauthorizedAccessException)
{
textBox2.Text = "Unauthorised Access";
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
}
private void button3_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text);
textBox1.Text = "";
}
private void button4_Click(object sender, EventArgs e)
{
richTextBox1.Text = serialPort1.ReadLine();
}
}
}
I'm able to send data from the above code but for reception I'm not able to read data from it. There are no build errors. Please help me out to solve this problem.
You can implement "SerialPortDataReceivedEvent" to read data from serial port.
Before opening connection to serial port register with "DataReceivedEvent", Inside
button1_Click event add below code.
serialPort1.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
Then add below event handler
private static void mySerialPort_DataReceived(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
//data received on serial port is asssigned to "indata" string
//Console.WriteLine("Received data:");
//Console.Write(indata);
}
Also, try to configure other properties like Parity, StopBits, DataBits etc. similar to the device on other end (with which you are trying to communicate).
Update data on UI:
what you need is a delegate method that sets the Text property of your text box with a given string. You then call that delegate from within your mySerialPort_DataReceivedhandler via the TextBox.Invoke() method. Something like this:
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
private void Form1_Load(object sender, EventArgs e)
{
//...
this.myDelegate = new AddDataDelegate(AddDataMethod);
}
public void AddDataMethod(String myString)
{
textbox1.AppendText(myString);
}
private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
textbox1.Invoke(this.myDelegate, new Object[] {indata});
}
Let us know if you need further clarification.
Hope this helps..
In my opinion, first just try test, when initing serial port add
serialPort1.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytesToRead = serialPort1.BytesToRead;
System.Diagnostics.Debug.WriteLine(bytesToRead);
}
after that in Output window you will sea is there any data in port or not

C# SERIAL PORT TEXTBOX ISSUE

I want to create a form having button,textbox,serialport in Visual c# 2010. My objective is when a button is pressed the data coming from the serial port has to displayed in textbox. I copied the following code from a tutorial. The textbox is not showing anything. Here's is the code
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;
namespace ser1
{
public partial class Form1 : Form
{
private string RxString;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// If the port is closed, don't try to send a character.
if (!serialPort1.IsOpen) return;
// If the port is Open, declare a char[] array with one element.
char[] buff = new char[1];
// Load element 0 with the key character.
buff[0] = e.KeyChar;
// Send the one character buffer.
serialPort1.Write(buff, 0, 1);
// Set the KeyPress event as handled so the character won't
// display locally. If you want it to display, omit the next line.
e.Handled = true;
}
private void DisplayText(object sender, EventArgs e)
{
textBox1.Text=RxString.Trim();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}'

Categories

Resources