在C#中實現UPnP(Universal Plug and Play,通用即插即用)的多設備協同工作,可以使用.NET Framework中的System.Net.Sockets
和System.Net.NetworkInformation
命名空間
首先,確保你的項目已經引用了System.Net.Sockets
和System.Net.NetworkInformation
命名空間。
創建一個類,用于處理UPnP設備的發現和通信。例如,創建一個名為UpnpDevice
的類,并添加以下屬性和方法:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class UpnpDevice
{
public string DeviceType { get; set; }
public string FriendlyName { get; set; }
public string Location { get; set; }
public string UDN { get; set; }
private Socket _socket;
public async Task DiscoverAsync()
{
// 創建一個UDP套接字
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
// 創建一個UPnP M-SEARCH消息
string searchMessage = $"M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 3\r\nST: {DeviceType}\r\n\r\n";
byte[] searchMessageBytes = Encoding.ASCII.GetBytes(searchMessage);
// 將消息發送到UPnP設備
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900);
await _socket.SendToAsync(new ArraySegment<byte>(searchMessageBytes), SocketFlags.None, endPoint);
// 接收設備響應
byte[] responseBuffer = new byte[1024];
while (true)
{
int bytesReceived = await _socket.ReceiveAsync(new ArraySegment<byte>(responseBuffer), SocketFlags.None);
string response = Encoding.ASCII.GetString(responseBuffer, 0, bytesReceived);
// 解析設備信息
if (response.Contains("HTTP/1.1 200 OK"))
{
string[] lines = response.Split('\r', '\n');
foreach (string line in lines)
{
if (line.StartsWith("LOCATION: "))
{
Location = line.Substring(10).Trim();
}
else if (line.StartsWith("FN: "))
{
FriendlyName = line.Substring(4).Trim();
}
else if (line.StartsWith("USN: "))
{
UDN = line.Substring(5).Trim();
}
}
// 處理設備信息,例如將其添加到列表或執行其他操作
Console.WriteLine($"Found device: {FriendlyName} ({Location})");
}
}
}
}
UpnpDevice
實例,并調用DiscoverAsync
方法來發現指定類型的UPnP設備。例如:using System;
class Program
{
static async Task Main(string[] args)
{
UpnpDevice upnpDevice = new UpnpDevice
{
DeviceType = "upnp:rootdevice" // 更改為所需的設備類型
};
await upnpDevice.DiscoverAsync();
}
}
這個示例將發現指定類型的UPnP設備,并打印出設備的友好名稱和位置。你可以根據需要修改代碼以處理多個設備并實現協同工作。