用C#接收广播消息 [英] Receiving a broadcast message in C#
本文介绍了用C#接收广播消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经尝试了很多,但是以某种方式接收远程主机广播的数据报的代码似乎有问题。
I have tried a lot, but somehow there seems to be some problem with the code to receive a datagram that is broadcast by a remote host.
所以有人可以请提供代码以使用UDP连接在C#中接收广播消息吗?
So could someone please provide me with the code to receive a broadcast message in C# using a UDP connection?
推荐答案
来自 http://www.java2s.com/Code/CSharp/Network/ReceiveBroadcast.htm
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class RecvBroadcst
{
public static void Main()
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive...");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
data = new byte[1024];
recv = sock.ReceiveFrom(data, ref ep);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
sock.Close();
}
}
这篇关于用C#接收广播消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文