UdpClient does not receive any data - c#

So, This has me confused for a while. I can't think of a simpler program to write and test. I initialize the UdpClient and call Receive method on a separate thread.Here is the complete code:
UdpClient client = new UdpClient(1414);
byte[] data = new byte[320];
IPEndPoint localpt = new IPEndPoint(IPAddress.Any,0);
const string START_COMMAND = "START";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
client.Connect("192.168.1.12",33051);
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
while (client.Available > 0)
{
data=client.Receive(ref localpt);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void button1_Click(object sender, EventArgs e)
{
byte[] START_BYTES = Encoding.ASCII.GetBytes(START_COMMAND);
client.Send(START_BYTES, START_BYTES.Length);
}
After setting a breakpoint on while (client.Available > 0) I noticed that client.Available is always zero.
Things that I've tried:
1-Check if I'm able to ping the remote host(OK I am able to Ping)
2-Check if there is any data available on the network interface(OK Used wireshark and saw incoming packets)
3-Check if my application is allowed to go through firewall(OK Explicitly added my exe to go through windows firewall)
4-Disable(Uninstall) any firewall or antivirus programs(OK)
Yet I cannot receive any data from inside my app. Through further investigation I found out that it is possible to send data(The remote host receives my data) but I can never receive any.

Related

How to get updates and reply telegram bot?

This is my code that i try to connect to a telegram bot
namespace telegramUpdate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TelegramBotClient bot = new TelegramBotClient("xxxxxxxxx");
int offset = 23;
Update temp = null;
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
try
{
var m = Task.Run(async()=> bot.GetUpdatesAsync(offset,50)).Result;
foreach (var x in m.Result)
{
switch (x.Type)
{
case UpdateType.MessageUpdate:
temp = x;
backgroundWorker1.ReportProgress(0);
bot.SendTextMessageAsync(x.Message.Chat.Id, ":)").ConfigureAwait(false);
break;
}
offset = x.Id+1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = temp.Message.From.FirstName;
}
}
}
after ruining message box show "One or more errors occurred." what is the problem? telegram bot should reply ":)" but it don't. I can not find out if m receive any updates or not.
try this:
bot.SendTextMessageAsync(x.Message.Chat.Id, ":)").GetAwaiter().GetResult();
you didn't execute the task. just it
to me this same error happen recently (the code was working on Feb 2020 but did not work later) when making bot.SendTextMessageAsync i received same exception. After some research i found this topic [Telegram Bot stops with An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll
that actually solved my problem.
using System.Net;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Close application after reading upper code c#

I am working with arduino serial monitor. My goal is to connect through serial port, send some data and close the application after it's done.
This is a C# application. Everything works well besides the fact that the application does not close. To solve the issue, I added Application.Exit() call at the end of Form1_Load method. After this change, the application starts and closes without reading the uppercase letter that I'm sending.
Source code:
namespace ForTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
SerialPort sp = new SerialPort(port, 9600, Parity.None, 8, StopBits.One);
try
{
sp.Open();
try
{
sp.WriteLine("Z"); // Send 1 to Arduino
sp.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ek)
{
System.Diagnostics.Debug.WriteLine(ek.Message);
}
}
Application.Exit();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
if I understood properly, you want to send data FROM C# to ARDUINO and then you exit the C# app
you can't just call Application.exit() after the InitializeComponent(), instead to achieve that you need to exit after sending the data
sp.WriteLine("Z"); // Send 1 to Arduino
sp.Close();
Application.Exit(); ///here!!

Capturing serial welcome message when connecting in c#

I am trying to write a program that communicates with a controller. The controller is supposed to send a "welcome" message when a connection is successfully established and, in fact, it does when I connect using a communications software. However, using the .NET code below, I never see the welcome message. Beyond that, it works. How can I capture this message. It seems to be sent the moment the connection is established.
Again, I am able to communicate fine with the controller after connection but I simply cannot seem to get the welcome message that is sent a the moment the connection is opened.
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
SerialPort sp;
public Form1()
{
InitializeComponent();
}
public void AddDataMethod(String myString)
{
richTextBox1.AppendText(myString);
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
sp = new SerialPort(comboBox1.SelectedItem.ToString(),Int32.Parse(comboBox2.SelectedItem.ToString()));
sp.DataReceived += SerialPort_OnDataReceived;
sp.Close();
sp.Open();
richTextBox1.AppendText("open\n");
button2.Enabled = true;
button3.Enabled = true;
}
catch (Exception ex)
{
richTextBox1.AppendText(ex.Message);
}
}
void SerialPort_OnDataReceived(object sender,SerialDataReceivedEventArgs args)
{
SerialPort sp = sender as SerialPort;
string s = sp.ReadExisting();
richTextBox1.Invoke(this.myDelegate, new Object[] { s });
}
private void button2_Click(object sender, EventArgs e)
{
sp.WriteLine(textBox1.Text);
textBox1.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
sp.Close();
richTextBox1.AppendText("\nclosed\n");
}
private void Form1_Load_1(object sender, EventArgs e)
{
this.myDelegate = new AddDataDelegate(AddDataMethod);
string[] Ports = SerialPort.GetPortNames();
comboBox2.SelectedIndex = comboBox2.Items.Count - 1;
Array.Sort(Ports, (a, b) => string.Compare(a.Substring(3).PadLeft(3, '0'), b.Substring(3).PadLeft(3, '0')));
foreach (string port in Ports)
{
comboBox1.Items.Add(port);
}
comboBox1.SelectedIndex = 0;
}
}
}
I worked it out. Required a slight delay between connection and trying to pull data from the port.

C# SerialPort class receives incorrect data

I currently have a program made using VB6 code that uses the MSCOMM control to pull back data from the serial port. This manages to successfully receive the data from my serial port, in which a Denso BHT-904B device is connected.
I am now trying to move this code over to C# so it fits in with a new piece of software that i am developing. To do this i am using the SerialPort class. However, the issue is that when i open the port up the data received event only fires when the device fails to communicate (which im guessing is due to a timeout). The data then received in the event is '↑↑↑↑↑'.
My SerialPort control settings are the following:
DtrEnable = True
PortName = COM3
ReadBufferSize = 1024
WriteBufferSize = 512
The code that i am using behind my form control is:
namespace BHTTestingDotNet
{
public partial class Form1 : Form
{
private string rxString;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
serialPort.DtrEnable = true;
serialPort.Encoding = Encoding.Default;
serialPort.DataReceived += serialPort_DataReceived;
serialPort.ErrorReceived += serialPort_ErrorReceived;
serialPort.Open();
}
private void serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
MessageBox.Show(e.ToString());
}
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
var serialPort = (SerialPort)sender;
var test = serialPort.BytesToRead;
SerialPort sr = (SerialPort)sender;
rxString = sr.ReadExisting();
this.BeginInvoke(new EventHandler(displayText));
}
private void displayText(object o, EventArgs e)
{
txtBHT.AppendText(rxString);
}
}
}
I have already tried to set both RtsEnable and DtrEnable to true but that didn't make any difference.
UPDATE - I have now changed to protocol settings on the device but i now only receive pipes and then a return symbol, for example like so:
|||||¬
I am using SerialPort class often and for my purposes I have made my own class
public class SerialPortDataSource : SerialPort
where SerialPort.DataReceived handler invoke this method:
private void SerialPortDataSource_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (BytesToRead > 0)
{
var buffor = new byte[BytesToRead];
Read(buffor, 0, buffor.Length);
_receivedBytes = buffor;
//wConsole.WriteLine(ArrayExtension.ToString(buffor));
var dataLogger = DataLogger;
if (dataLogger != null)
{
dataLogger.WriteLine("- DR - {0}", true, BitConverterExtension.ToHexString(buffor));
}
if (OnDataReceived != null)
{
OnDataReceived(this, buffor);
}
}
}
catch (InvalidOperationException)
{
// sometimes DataReceived event is invoked after port is closed which causes InvalidOperationException
}
}
This method is working for me in many applications with variety serial port settings.

tcpClient and IRC client issues

Can someone tell me why the following code isn't working?
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TCPClient {
public partial class Form1 : Form {
private TcpClient client;
private Thread readThread;
private NetworkStream stream;
private Stream dataStream;
private Encoding dataStreamEncoding;
private StreamWriter writer;
private StreamReader reader;
public Form1() {
InitializeComponent();
this.client = new TcpClient();
this.readThread = new Thread(ReadLoop);
this.dataStreamEncoding = Encoding.Default;
Thread.CurrentThread.Name = "MainThread";
this.readThread.Name = "ReadThread";
}
private void btnConnect_Click(object sender, EventArgs e) {
if (this.client != null && !this.client.Connected) {
try {
this.client.Connect("open.ircnet.net", 6666);
if (this.client != null && this.client.Connected) {
Console.WriteLine("Connected");
}
// Set up network I/O objects.
this.stream = this.client.GetStream();
this.writer = new StreamWriter(this.stream, this.dataStreamEncoding);
this.reader = new StreamReader(this.stream, this.dataStreamEncoding);
//HandleClientConnected(state.Item3);
this.readThread.Start();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
private void btnPing_Click(object sender, EventArgs e) {
Console.WriteLine("Ping Sent");
this.writer.Write("PING");
this.writer.Flush();
}
private void btnLogin_Click(object sender, EventArgs e) {
Console.WriteLine("Login Info Sent");
this.writer.Write( "PASS *\r\n" +
"NICK testing3134\r\n" +
"USER guest 8 * :\"John Doe\"");
this.writer.Flush();
}
private void ReadLoop() {
try {
// Read each message from network stream, one per line, until client is disconnected.
while (this.client != null && this.client.Connected) {
var line = this.reader.ReadLine();
if (line == null)
break;
Console.WriteLine(line);
}
if(!this.client.Connected) {
Console.WriteLine("Disconnected");
}
} catch(Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
}
Console:
Connected
:ircnet.eversible.com 020 * :Please wait while we process your connection to ircnet.eversible.com
Login Info Sent
Ping Sent
The thread 'ReadThread' (0x10bc) has exited with code 0 (0x0).
ERROR :Closing Link: testing3134[unknown#24.255.34.216] (Ping timeout)
Changes that made it work:
Original:
private void btnPing_Click(object sender, EventArgs e) {
Console.WriteLine("Ping Sent");
this.writer.Write("PING");
this.writer.Flush();
}
private void btnLogin_Click(object sender, EventArgs e) {
Console.WriteLine("Login Info Sent");
this.writer.Write( "PASS *\r\n" +
"NICK testing3134\r\n" +
"USER guest 8 * :\"John Doe\"");
this.writer.Flush();
}
WORKING:
private void btnPing_Click(object sender, EventArgs e) {
Console.WriteLine("Ping Sent");
this.writer.WriteLine("PING\r\n");
this.writer.Flush();
}
private void btnLogin_Click(object sender, EventArgs e) {
Console.WriteLine("Login Info Sent");
this.writer.WriteLine("PASS *\r\n");
this.writer.Flush();
this.writer.WriteLine("NICK testing3134\r\n");
this.writer.Flush();
this.writer.WriteLine("USER guest 8 * :\"John Doe\"\r\n");
this.writer.Flush();
}
Not only did I switch from Write to WriteLine but like the accepted answer suggests I add line returns to the end of all the requests being sent.
You're not including a line break after the PING or USER messages.
From RFC 2812:
IRC messages are always lines of characters terminated with a CR-LF (Carriage Return - Line Feed) pair
So you should have:
this.writer.Write("PASS *\r\n" +
"NICK testing3134\r\n" +
"USER guest 8 * :\"John Doe\"\r\n");
and:
this.writer.Write("PING\r\n");
I'd also avoid using Encoding.Default if I were you. The RFC specifies that no particular character encoding is used, but it does expect it to be an 8-bit one (rather than potentially multi-byte). This is a poor way of specifying an encoding, but I'd probably use either ASCII or ISO-8859-1 explicitly.
SOmething else to consider here is that most irc servers send you a "ping cookie" when you connect. This consists of a PING message with a random string as its parameter. You MUST respond to this with a PONG containing the same random string, or your connection will be terminated with a "Ping Timeout" message. This is a simple method of preventing fire-and-forget use of irc through proxies, and is very common.
You should add functionality to work with this into your client.

Categories

Resources