Maui- - indicator ifserver is conected

דני שטרית 2,646 Reputation points
2024-02-29T09:40:59.6466667+00:00

Hi, I want to show if server is conected or not . How is can be done ? which control to use, button is clickable and i want it will be clickable? Thanks,

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,819 questions
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 34,461 Reputation points Microsoft Vendor
    2024-03-01T05:23:49.4433333+00:00

    Hello,

    You could monitor the server connection status through data binding and timer callback functions.

    Please refer to the following code:

    <Label
        Text="{Binding Connection.Connection}"
        Background="{Binding Connection.ConnectionColor}"
        Style="{StaticResource Headline}"/>
    
    
     public class ConnectionAble
        {
            public string Connection { get; set; }
            public Color ConnectionColor {  get; set; }
        }
        public class TestViewModel : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler? PropertyChanged;
    
            private ConnectionAble connection;
            private Timer _timer;
    
            public ConnectionAble Connection
            {
                get => connection;
                set
                {
                    if (connection != value)
                    {
                        connection = value;
                        OnPropertyChanged(); // reports this property
                    }
                }
            }
            public void OnPropertyChanged([CallerMemberName] string name = "") =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            public TestViewModel()
            {
    
    
                // Update the DateTime property every second.
                _timer = new Timer(new TimerCallback(async (x) => await CheckConnection(x)),
                                   null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
            }
    
            private async Task CheckConnection(object state)
            {
                Timer t = (Timer)state;
                if(t != null)
                {
                    t.Dispose();
                }
               
                bool isIpViliable = await IsIpReachable("your server ip");
                bool isPortViliable = await IsPortReachable("server ip",port);
                if(isIpViliable && isPortViliable)
                {
                    Connection = new ConnectionAble{ Connection = "Connected", ConnectionColor = Color.Parse("Green") };
                }
                else
                {
                    Connection = new ConnectionAble{ Connection = "Not Connected", ConnectionColor = Color.Parse("Red") };
                }
               
            }
            public async Task<bool> IsIpReachable(string strIP)
            {
                Ping pingSender = new Ping();
                PingOptions options = new PingOptions();
                // Use the default Ttl value which is 128,
                // but change the fragmentation behavior.
                options.DontFragment = true;
                // Create a buffer of 32 bytes of data to be transmitted.
                string data = "test";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 1500;
                PingReply reply = pingSender.Send(strIP, timeout, buffer, options);
                return (reply.Status == IPStatus.Success);
            }
    
            public async Task<bool> IsPortReachable(string host, int port = 80, int msTimeout = 2000)
            {
                return await Task.Run(() =>
                {
                    var clientDone = new ManualResetEvent(false);
                    var reachable = false;
                    var hostEntry = new DnsEndPoint(host, port);
                    using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                    {
                        var socketEventArg = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry };
                        socketEventArg.Completed += (s, e) =>
                        {
                            reachable = e.SocketError == SocketError.Success;
                            clientDone.Set();
                        };
                        clientDone.Reset();
                        socket.ConnectAsync(socketEventArg);
                        clientDone.WaitOne(msTimeout);
                        return reachable;
                    }
                });
            }
        }
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful