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.