收到UDP数据时调用函数。 [英] Calling a function when UDP data recieved.

查看:111
本文介绍了收到UDP数据时调用函数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,在c#编程方面仍然不成熟,我编写了一个应用程序,它使用UDP协议从arduino接收数据,当我点击一个按钮数据发送和接收没有障碍,但我希望我的应用程序接收数据当arduino发送它时自动。所以我不会点击任何按钮或我不必手动触发任何事件。这是总代码。 PS即时通讯使用Visual Studio 2010 Express。





只有在arduino发送数据时才有办法接收数据吗?

请帮助



我尝试过:



< pre lang =c#> private void button1_Click( object sender,EventArgs e)
{
try
{
Socket SOCK = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
SOCK.ReceiveTimeout = 2000 ;
SOCK.SendTimeout = 2000 ;
IPAddress serverAddres = IPAddress.Parse( 192.168.1.177);
IPEndPoint endPoint = new IPEndPoint(serverAddres, 23 );
String text = textBox1.Text;
byte [] sendBuffer = Encoding.ASCII.GetBytes(text);
SOCK.SendTo(sendBuffer,endPoint);
byte [] recievedByte = new byte [ 1024 ];
int bytesrec = SOCK.Receive(recievedByte);
textBox1.Text = Encoding.UTF8.GetString(recievedByte, 0 ,bytesrec);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, 错误,MessageBoxButtons.RetryCancel,MessageBoxIcon.Error);
}

}

解决方案

您需要附加异步回调 1 ,代表它接收套接字的数据,然后提醒您已收到数据。您无法附加接收功能,因为它可能会阻塞。您可以争辩说,

  //  您的收到调用也没用,所以就是这样, 
SOCK.Receive(buffer,offset,SOCK.Available,SocketFlags.None);

会读取字节,但是不,因为即使在这种情况下,可用将为0,因为设备可能尚未发送消息,因此它将返回,充当非阻塞呼叫。一个好方法是使用回调,并执行BeginReceive(...),并从线路异步读取,

  //   Microsoft文档中的代码 
// 开始从远程设备接收数据。
client.BeginReceive(state.buffer, 0 ,StateObject.BufferSize, 0
new AsyncCallback(ReceiveCallback),state);

请查看此文档以了解有关该主题的更多信息,异步客户端套接字示例| Microsoft Docs [ ^ ],如果您将其作为服务器应用程序写入,请仔细阅读,异步服务器套接字示例| Microsoft Docs [ ^ ]



1。我用斜体来表示,因为在21世纪考虑回调和异步方法很有趣。


Hi there, still not mature in c# programming, i have written an application in which it receives data from arduino using UDP protocol, when i click a button data is sent and received without hurdle, but i want my application to receive data automatically when arduino sends it. so that i wont click any button or i dont have to trigger any events manually. here is the total code. PS im using Visual Studio 2010 Express.


is there a way to receive data only when arduino sends it?
please help

What I have tried:

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Socket SOCK = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                SOCK.ReceiveTimeout = 2000;
                SOCK.SendTimeout = 2000;
                IPAddress serverAddres = IPAddress.Parse("192.168.1.177");
                IPEndPoint endPoint = new IPEndPoint(serverAddres, 23);
                String text = textBox1.Text;
                byte[] sendBuffer = Encoding.ASCII.GetBytes(text);
                SOCK.SendTo(sendBuffer, endPoint);
                byte[] recievedByte = new byte[1024];
                int bytesrec = SOCK.Receive(recievedByte);
                textBox1.Text = Encoding.UTF8.GetString(recievedByte, 0, bytesrec);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
            }

        }

解决方案

You need to attach the async callback1, that receives the data for your socket, on its behalf and then alerts you that data has been received. You cannot attach a receive function, as it might be blocking. You can argue, that,

// Your receive call is useless as well, and so would be this, 
SOCK.Receive(buffer, offset, SOCK.Available, SocketFlags.None);

would read the bytes, but no, because even in this case, Available will be 0 as the device might have not yet sent a message, thus it will return, acting as a non-blocking call. A good approach is to use a callback, and do a BeginReceive(...), and asynchronously read from the wire,

// Code from Microsoft documentations
// Begin receiving the data from the remote device.  
client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,  
     new AsyncCallback(ReceiveCallback), state);  

Please review this documentation to learn a bit more on the topic, Asynchronous Client Socket Example | Microsoft Docs[^], and if you are writin this as a server application, then go through this, Asynchronous Server Socket Example | Microsoft Docs[^]

1. I italicized that, because it is funny to consider a callback, and asynchronous approach in 21st century.


这篇关于收到UDP数据时调用函数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆