Я использую Rider на Mac, и у меня возникли некоторые проблемы с невозможностью принимать трансляции на порту 15000, только в приложении MAUI. Вот code в консольном решении:
который работает идеально и быстро, как и ожидалось.
Однако, когда я запускаю его в приложении MAUI, либо в отдельном файле CS и использую его, либо имея его в файле MainPage.xaml.cs, он либо не работает, либо выдает мне отказ в доступе. Вот несколько примеров:
и я просто получаю:
2024-08-19 22:22:11.728 InfiniteConnect[23296:525617] Исключение: Отказано в доступе
Я проверил все брандмауэры и настройки и т. д., но сообщите мне, если я что-то пропустил.
MainPage.xaml.cs:
Но я просто получаю:
Оба они должны возвращать некоторые данные, которые я затем деcodeирую, но даже не прохожу дальше: udp = new UdpClient(15000); in 2
Я провел много исследований по этому поводу, но ничего не работает. Документация по получению пакетов следующая: Если IP-адрес устройства для подключения неизвестен, можно обнаружить существующие устройства в той же локальной сети с помощью UDP. Мы передаем UDP-пакеты на порт 15000, которые содержат IP-адрес устройства и другие сведения.
Спасибо.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Newtonsoft.Json; // Add this if using Newtonsoft.Json for JSON parsing
public class IFConnect
{
private UdpClient udpClient;
private IPEndPoint endPoint;
private string device_ip;
public void EstablishConnection(bool logStatus = false)
{
udpClient = new UdpClient(15000);
endPoint = new IPEndPoint(IPAddress.Any, 15000);
if (logStatus)
Console.WriteLine("Connecting to Infinite Flight...");
StartListening();
}
private void StartListening()
{
udpClient.BeginReceive(new AsyncCallback(OnUdpDataReceived), null);
}
private void OnUdpDataReceived(IAsyncResult ar)
{
byte[] data = udpClient.EndReceive(ar, ref endPoint);
string receivedData = Encoding.UTF8.GetString(data);
Console.WriteLine($"Received '{receivedData}' from {endPoint}");
// Example processing: Parsing JSON (assuming the data is JSON-formatted)
dynamic response = JsonConvert.DeserializeObject(receivedData);
string addr = GetIPAddr(response.Addresses ?? response.addresses);
Console.WriteLine(response);
Console.WriteLine(addr);
if (!string.IsNullOrEmpty(addr) && (response.Port != null || response.port != null))
{
device_ip = addr;
// Proceed with TCP connection or any other logic here
// ConnectAPI();
}
// Continue listening for the next UDP packet
StartListening();
}
private string GetIPAddr(dynamic addresses)
{
// Add your logic to extract and return the IP address
return addresses[0].ToString(); // Example logic
}
}
class Program
{
static void Main(string[] args)
{
IFConnect ifConnect = new IFConnect();
ifConnect.EstablishConnection(true); // Pass 'true' to log status
Console.ReadLine(); // Keep the console open
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Ensure you have this package installed
using Microsoft.Maui.Controls; // Ensure you are using the correct namespace for MAUI
namespace InfiniteConnect
{
public partial class MainPage : ContentPage
{
private UdpClient udpClient;
private IPEndPoint endPoint;
private string device_ip;
public MainPage()
{
InitializeComponent();
StartUdpClient();
}
private async void StartUdpClient()
{
try
{
udpClient = new UdpClient(15000);
endPoint = new IPEndPoint(IPAddress.Any, 15000);
// Start receiving data asynchronously
await Task.Run(() => ListenForMessages());
}
catch (Exception ex)
{
// Handle exceptions if needed
Console.WriteLine($"Exception: {ex.Message}");
}
}
private async void ListenForMessages()
{
while (true)
{
try
{
var data = await udpClient.ReceiveAsync();
var receivedData = Encoding.UTF8.GetString(data.Buffer);
// Process received data
await ProcessReceivedData(receivedData);
}
catch (Exception ex)
{
// Handle exceptions if needed
Console.WriteLine($"Exception: {ex.Message}");
}
}
}
private async Task ProcessReceivedData(string data)
{
// This method should run on the main thread if it updates UI components
await MainThread.InvokeOnMainThreadAsync(() =>
{
Console.WriteLine($"Received '{data}' from {endPoint}");
dynamic response = JsonConvert.DeserializeObject(data);
string addr = GetIPAddr(response.Addresses ?? response.addresses);
Console.WriteLine(response);
Console.WriteLine(addr);
if (!string.IsNullOrEmpty(addr) && (response.Port != null || response.port != null))
{
device_ip = addr;
// Update UI or handle connection logic here
}
});
}
private string GetIPAddr(dynamic addresses)
{
// Add your logic to extract and return the IP address
return addresses[0].ToString(); // Example logic
}
}
}
// IFConnect.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Newtonsoft.Json;
public class IFConnect
{
public class Data
{
public Data(dynamic data)
{
// Initialize your Data object with the data here
}
}
private string device_ip;
private int device_port = 15000; // Assuming the port is 15000, set it as required
private TcpClient tcp;
private UdpClient udp;
private dynamic device_info;
private Data info;
public string Connect(string deviceIp = null)
{
Console.WriteLine("Starting connection process...");
if (string.IsNullOrEmpty(deviceIp))
{
Console.WriteLine("No device IP provided, discovering devices...");
udp = new UdpClient(15000);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 15000);
while (true)
{
byte[] receivedBytes = udp.Receive(ref remoteEndPoint);
if (receivedBytes != null && receivedBytes.Length > 0)
{
string receivedData = Encoding.UTF8.GetString(receivedBytes);
device_info = JsonConvert.DeserializeObject(receivedData);
info = new Data(device_info);
device_ip = remoteEndPoint.Address.ToString();
Console.WriteLine($"Device found: {device_info["DeviceName"]}, IP: {device_ip}");
udp.Close();
break;
}
}
}
else
{
device_ip = deviceIp;
Console.WriteLine($"Using provided device IP: {device_ip}");
}
try
{
tcp = new TcpClient();
tcp.Connect(device_ip, device_port);
Console.WriteLine($"Connected to Infinite Flight Connect: {device_info["DeviceName"]}, IP: {device_ip}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to connect: {ex.Message}");
return "Connection failed.";
}
// shutdown_tcp(); // Implement this method if needed
return "Connected! Have a nice flight!";
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Ensure you have this package installed
using Microsoft.Maui.Controls; // Ensure you are using the correct namespace for MAUI
namespace InfiniteConnect
{
public partial class MainPage : ContentPage
{
private UdpClient udpClient;
private IPEndPoint endPoint;
private string device_ip;
public MainPage()
{
InitializeComponent();
IFConnect ifc = new IFConnect();
// Start the connection process
Task.Run(() =>
{
string deviceIp = null;
ifc.Connect(deviceIp);
});
}
}
}
2024-08-19 22:23:52.746 InfiniteConnect[23399:527862] Starting connection process...
2024-08-19 22:23:52.746 InfiniteConnect[23399:527862] No device IP provided, discovering devices...