[C#.NET][TCP Socket] 接收 Alien Reader UDP 廣播封包
我們可以利用 Socket 類別,處理UDP廣播封包,處理的方法很簡單,步驟如下:
Step1.初始化執行個體:
Step2.用 Receive 前綴字方法接收封包:
Step3.將封包轉成字串:
encoding.GetString(receiveBuffer, 0, dataLength);
實做程式碼如下:
private bool IsReceive = true;
private List<string> _broadcastPackages = new List<string>();
public IEnumerable<string> BroadcastPackages
{
get { return this._broadcastPackages; }
}
private void getBroadcastPackage(int UdpPort)
{
Encoding encoding = Encoding.UTF8;
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, UdpPort);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
clientSocket.Bind(ipEndPoint);
EndPoint endPoint = (EndPoint)ipEndPoint;
var receiveLength = clientSocket.ReceiveBufferSize;
byte[] receiveBuffer = new byte[receiveLength];
try
{
while (IsReceive)
{
int dataLength = clientSocket.ReceiveFrom(receiveBuffer, ref endPoint);
var dataPackage = encoding.GetString(receiveBuffer, 0, dataLength);
var query = (from package in BroadcastPackages
where package == dataPackage
select package).FirstOrDefault();
//var query = this.BroadcastPackages.Select(package => new { Package = package }).FirstOrDefault(item => item.Package == dataPackage);
if (query == null)
{
this._broadcastPackages.Add(dataPackage);
}
}
}
finally
{
clientSocket.Close();
}
}
接收結果:
取得IP
取得封包內容
很明顯的看出,這是 Alien Reader 的廣播封包,有了這封包訊息,便能進行更進一步的處理。
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET