this is my first post, sorry in advance if I do something I shouldn't. I always search here for answer but this time I saw nothing about my problem. I have a project in C# where I keep alive a connection UDP listening a multicast IP from a data streaming.
The IP I'm listening is a multicast streamer that sends tracking data from many tracking systems, so we can assume the sender is not the problem. It sends like 1024 bytes packets, 60 fps.
This is a small example extracted from the whole project, simplified and as far as I tested, behaves in the same way as in the big project. The problem is that if I connect in localhost this never break, but if I connect to remote IPs this stop working, more or less, in 4 minutes.
public class TrackingStateObject
{
public Socket workSocket = null;
public const int BUFFER_SIZE = 65507;
public byte[] buffer = new byte[BUFFER_SIZE];
}
class MainClass
{
static public string multicastServerIPAddress = "239.255.42.99";
static public string realTrackingServerIPAddress = "161.116.27.144";
static protected EndPoint trackingEndPoint;
static public int dataPort = 2345;
static protected Socket sockData = null;
static int foo = 0;
public static void Main (string[] args)
{
IPEndPoint ipep;
TrackingStateObject so;
IPAddress trackingIP = IPAddress.Parse(multicastServerIPAddress);
trackingEndPoint = new IPEndPoint(trackingIP, dataPort);
sockData = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
ipep = new IPEndPoint(IPAddress.Any, dataPort);
try {
sockData.Bind(ipep);
}
catch (Exception ex) {
System.Console.WriteLine("[UDPClient] Exception "+ex.Message);
return;
}
sockData.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(trackingIP));
try {
trackingIP = IPAddress.Parse(realTrackingServerIPAddress);
trackingEndPoint = new IPEndPoint(trackingIP, dataPort);
}
catch(Exception ex) {
System.Console.WriteLine("[UDPClient] Exception "+ex.Message);
return;
}
so = new TrackingStateObject();
so.workSocket = sockData;
sockData.BeginReceiveFrom(so.buffer, 0, TrackingStateObject.BUFFER_SIZE, 0, ref trackingEndPoint, new AsyncCallback(AsyncReceiveCallback), so);
System.Threading.Thread.Sleep (600000);
}
private static void AsyncReceiveCallback(IAsyncResult ar)
{
try {
TrackingStateObject so = (TrackingStateObject)ar.AsyncState;
Socket sock = so.workSocket;
int read = sock.EndReceiveFrom(ar, ref trackingEndPoint);
if (read > 0)
{
// Do things with the data
System.Console.WriteLine("Recieved shit, " + read + " bytes, " + foo++ + " times.");
}
sock.BeginReceiveFrom(so.buffer, 0, TrackingStateObject.BUFFER_SIZE, SocketFlags.None, ref trackingEndPoint, new AsyncCallback(AsyncReceiveCallback), so);
}
catch (Exception e) {
System.Console.WriteLine("[UDPClient] Exception AsynCallback "+e.Message);
}
}
}
I debugged for a while and as far I can see is that always sock.BeginReceiveFrom is called, stop in some point, AsyncReceiveCallback is never executed again. Perhaps I'm doing here something stupid, but in any case, I'm not able to see it. Thanks!
I was having exactly the same problem, which only seems to occur on WiFi interfaces, not hardwired interfaces. The solution I discovered was to always set the SocketOptionName.AddMembership option before calling BeginReceiveFrom().
In the receive callback, after calling EndReceiveFrom() then set the SocketOptionName.DropMembership option for the multicast address.
Then before calling BeginReceiveFrom() again, set the SocketOptionName.AddMembership option.
Not sure why this has to be done for WiFi interfaces, but it worked for me.
Related
In my HoloLens2 application sometimes the UDP-Package-receive rate drops instantly from 40 packages per second to 0-2 packages per second and stays there (size of packages between 2000 byte and 60000 byte. The application is made with Unity3d and .Net Sockets for networking. This behaviour sometimes happens straight from application startup, sometimes after 30 minutes, so basically quiet random. Even Restarting HoloLens2 doesn´t help in such a situation. The application logs no exception or error messages. On my Unity-Editor the Application can handle the network traffic without any problem.
It feels like some Network buffer got stuffend and drops all packages so did I miss some Cleanup command in my Networking-Code or is there another way to face Receive-Overload in my code?
Or is HoloLens2 somehow limited in it´s Bandwith when running via Ethernet (and not Wifi)?
At the same time my application also maintains a peer-to-peer Video-stream (WebRTC with MixedReality Capture). This stream works well over the whole lifetime of the application flawlessly.
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
public class UdpCommunicationDotNet : ICommunicator
{
#region Fields
private int m_PackageCountPerSecond;
private int m_PackageCountTotal;
private Thread m_PackageCounterResetRoutine;
private Socket m_SenderSocket;
private Socket m_ReceiverSocket;
private IPEndPoint m_ServerIpEndPoint;
private IPEndPoint m_ReceiverIpEndPoint;
private IPEndPoint m_ListenerIpEndPoint;
private EndPoint m_ServerEndPoint;
private EndPoint m_ReceiverEndPoint;
private byte[] m_ReceiveBuffer;
private IDataProvider m_DataProvider;
private int m_MaxBufferByteLength;
private bool m_ReceiveEnabled = true;
public IDataProvider DataProvider { get => m_DataProvider; set => m_DataProvider = value; }
#endregion
#region Constructor
public UdpCommunicationDotNet()
{
m_MaxBufferByteLength = GameManager.Instance.GetConfigurationManager.RuntimeConfig.NetworkSettings.MaxBufferByteLength;
}
#endregion
#region Public Methods
public void Initialize(DataLineConfig dataLineConfig)
{
m_ReceiveBuffer = new byte[m_MaxBufferByteLength];
m_ServerIpEndPoint = dataLineConfig.serverEndPoint;
m_ReceiverIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
m_ServerEndPoint = (EndPoint)m_ServerIpEndPoint;
m_ReceiverEndPoint = (EndPoint)m_ReceiverIpEndPoint;
m_ListenerIpEndPoint = dataLineConfig.receiverEndPoint;
}
public void StartReceiver()
{
if (InitializeReceiverSocket())
{
m_ReceiveEnabled = true;
StartReceiving();
}
}
public void EndReceiver()
{
m_ReceiveEnabled = false;
}
public void StartSender()
{
InitializeSenderSocket();
}
public void Send(Byte[] data)
{
try
{
//added this, remove it
//Debug.Log("SentMyDataPackage");
m_SenderSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, m_ServerEndPoint, new AsyncCallback(OnSendCallback), null);
}
catch (Exception e)
{
Debug.LogError("Failed to send udp data through the UdpCommunicator: " + e.Message);
}
}
#endregion
#region Private Methods
private bool InitializeReceiverSocket()
{
bool isInitialized = false;
try
{
m_ReceiverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
m_ReceiverSocket.Bind(m_ListenerIpEndPoint);
isInitialized = true;
}
catch (Exception e)
{
Debug.LogError("Failed to initialize the receiver socket in the UdpCommunicator: " + e.Message);
}
return isInitialized;
}
private void InitializeSenderSocket()
{
m_SenderSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
private void StartReceiving()
{
m_ReceiverSocket.BeginReceiveFrom(m_ReceiveBuffer, 0, m_ReceiveBuffer.Length, SocketFlags.None, ref m_ReceiverEndPoint, new AsyncCallback(OnReceiveCallback), m_ReceiverEndPoint);
}
private void DistributeData(object dataObject)
{
byte[] data = (byte[])dataObject;
m_DataProvider.DistributeData(data);
}
#endregion
#region Callback Methods
private void OnSendCallback(IAsyncResult asyncResult)
{
try
{
m_SenderSocket.EndSend(asyncResult);
}
catch (Exception e)
{
Debug.LogError("Failed to close the opened send connection in the UdpCommunicator: " + e.Message);
}
}
private void OnReceiveCallback(IAsyncResult asyncResult)
{
try
{
if (DebugManager.Instance.isActive)
{
DebugManager.Instance.m_PackageCounter.UpdateMainCountTotal(m_PackageCountTotal);
}
int receivedBufferSize = m_ReceiverSocket.EndReceiveFrom(asyncResult, ref m_ReceiverEndPoint);
Array.Resize(ref m_ReceiveBuffer, receivedBufferSize);
byte[] copiedBuffer = new byte[receivedBufferSize];
Buffer.BlockCopy(m_ReceiveBuffer, 0, copiedBuffer, 0, receivedBufferSize);
Thread thread = new Thread(DistributeData);
thread.SetApartmentState(ApartmentState.STA);
thread.Start(copiedBuffer);
m_ReceiveBuffer = new byte[m_MaxBufferByteLength];
}
catch (Exception e)
{
Debug.LogError("Failed to fetch the received data in the UdpCommunicator: " + e.Message);
}
finally
{
if (m_ReceiveEnabled)
{
StartReceiving();
}
else
{
m_ReceiverSocket.Shutdown(SocketShutdown.Both);
m_SenderSocket.Shutdown(SocketShutdown.Both);
m_ReceiverSocket.Close();
m_SenderSocket.Close();
}
}
}
#endregion
}
Edit:
By writing the Minimal Reproducable Example I found out the reason for the missbehaviour! I realized that if I send more than 4 Packages in one chunk (so send package1, send package2, send package3, send package4, etc, wait x ms, start again) HoloLens2 is starting to drop my udp packages.
In contrast, when I send Package1-> wait for 4 ms -> send package2 -> wait for 4 ms -> send package 3 -> wait 4ms and so on and after sending all different packages simply restart sending, it Works like a charm!
Also, when I send the packages via EthernetOverUSB (what is not a usable approach for my case), even if I send all packages in one chunk it works.
For me this behaviour is wiered and I can´t explain it to myself. Maybe somebody of you can ? Anyways, thanks for anybody who tried to help me!
I have tried to make my first asynchronous socket program on C#, despite no error on the code, it does not accept connections. I have checked by Telnet.
this is my TCP server code:
I have just seen some samples on the internet but I could not find my problem, I believe that some thing else should add to my code.
class Program
{
static byte[] Mybuffer = new byte[4096];
static TcpClient tc = new TcpClient();
private static void PrintUsageInfo()
{
}
static void Main(string[] args)
{
TcpListener tl = new TcpListener(IPAddress.Parse("192.168.1.141"), 8008);
tl.Start();
tl.BeginAcceptTcpClient(OnCompleteTCP, tl);
}
static void OnCompleteReadData(IAsyncResult isa)
{
int countreadbytes = 0;
try
{
//TcpClient tc;
tc = (TcpClient)isa.AsyncState;
countreadbytes = tc.GetStream().EndRead(isa);
if (countreadbytes==0)
{
Console.WriteLine("USER Disconnected");
//client disconnect
return;
}
//continue to get data
tc.GetStream().BeginRead(Mybuffer, 0, Mybuffer.Length, OnCompleteReadData, tc);
Console.Write(Encoding.ASCII.GetString(Mybuffer));
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
static void OnCompleteTCP(IAsyncResult isa)
{
TcpListener tcpl = (TcpListener)isa.AsyncState;
tc=tcpl.EndAcceptTcpClient(isa);
tc.GetStream().BeginRead(Mybuffer, 0, Mybuffer.Length, OnCompleteReadData, tc);
}
}
So what is the problem?
Thanks to Caius Jard i have checked the netstat -a to see all listening ports and my port was not there. So I found out that this might be a problem on running process. I put the BeginAcceptTcpclient on a while(true) loop and it is working well now!
static void Main(string[] args)
{
TcpListener tl = new TcpListener(IPAddress.Any, 8008);
tl.Start();
while (true) { tl.BeginAcceptTcpClient(OnCompleteTCP, tl); }
}
I am currently developing a C# TCP Server application for my game. The Server functions perfectly for a long period of time, closes however unexpectedly after about a day or 2 of running. I've furthermore printed the console output to a file, which I checked after the application closed, and there were no errors, or at least none were printed. The Code for the server is the following :
class Program
{
private static Thread consoleThread;
static void Main(string[] args)
{
//To get the output in a file
FileStream filestream = new FileStream("out.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
InitializeConsoleThread();
ServerHandleData.InitializePacketListener();
ServerTCP.InitializeServer();
}
private static void InitializeConsoleThread()
{
consoleThread = new Thread(ConsoleLoop);
consoleThread.Name = "ConsoleThread";
consoleThread.Start();
}
private static void ConsoleLoop()
{
while (true)
{
}
}
}
The TCP Clients are handled with the following async methods :
private static void InitializeServerSocket()
{
ServerSocket = new TcpListener(IPAddress.Any, 8080);
ServerSocket.Start();
ServerSocket.BeginAcceptTcpClient(ClientConnectCallback, null); //Once we get a connection, ClientConnectCallback is called
}
private static void ClientConnectCallback(IAsyncResult result)
{
TcpClient tempClient = ServerSocket.EndAcceptTcpClient(result); //Accepts the connection and creates its corresponding TcpClient
ServerSocket.BeginAcceptTcpClient(ClientConnectCallback, null); //Open the connection again for other players
string[] IPs = tempClient.Client.RemoteEndPoint.ToString().Split(':');
if(IPDictionary.TryGetValue(IPs[0], out ClientObject C))
{
C.Socket = tempClient;
C.Socket.NoDelay = true;
C.Socket.ReceiveBufferSize = 4096;
C.Socket.SendBufferSize = 4096;
C.ReceiveBuffer = new byte[4096];
C.myStream = C.Socket.GetStream();
C.IP = tempClient.Client.RemoteEndPoint.ToString();
C.myStream.BeginRead(C.ReceiveBuffer, 0, C.Socket.ReceiveBufferSize, C.ReceiveCallback, null);
PACKET_SendMessage(C.ConnectionID, "CheckIP", 0, IPs[0]);
Console.WriteLine("Connection incoming from {0}", C.IP);
return;
}
Random ran = new Random();
int curID = ran.Next(); //random signed int
while (curID == 0 || ClientObjects.ContainsKey(curID)) { curID = ran.Next(); }
ClientObjects[curID] = new ClientObject(tempClient, curID);
TempPlayers[curID] = new TempPlayer();
}
which are called in the Program class with the initializeServer methods.
The Server functions well for a while and then suddenly closes, seemingly without any reason. The only cause I could find while searching on the internet is that the program eventually runs out of memory and just closes. Wouldn't however the garbage collector integrated in C# prevent such a thing ? Thank you all for your help in advance, I hope I made the question as direct and as clear as possible. Furthermore, if there are any other ways to improve these snippets of code, please do tell.
I am trying to develop an application in android to sent the gps data to my pc .the android part is :
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
float latitude = (float) (location.getLatitude());
float longitude = (float) (location.getLongitude());
showMessage("Student Details", "Latitude: " + latitude + ", Longitude: " + longitude);
Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
try {
Socket socket = new Socket("192.168.1.5",5000);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("HELLO_WORLD");
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And the c# code or server code is :
public AsyncCallback pfnWorkerCallBack;
private Socket m_mainSocket;
private Socket[] m_workerSocket = new Socket[25];
private int m_clientCount = 0;
private string ipaddress;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
startfun();
}
public void startfun()
{
try
{
// DrawMapPersian();
ipaddress = "192.168.1.5";
// Check the port value
string portStr = "5000";
int port = System.Convert.ToInt32(portStr);
// Create the listening socket...
m_mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
// Bind to local IP Address...
m_mainSocket.Bind(ipLocal);
listBox1.Items.Add("Server Started...");
// Start listening...
m_mainSocket.Listen(20);
listBox1.Items.Add("Server Listening for ...");
// Create the call back for any client connections...
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (Exception qqq)
{
using (StreamWriter writer =
new StreamWriter(#"e:\a.txt"))
{
writer.Write(qqq.Message);
}
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;
// Complete the BeginReceive() asynchronous call by EndReceive() method
// which will return the number of characters written to the stream
// by the client
iRx = socketData.m_currentSocket.EndReceive(asyn);
string res = GetParameters(socketData.dataBuffer);
Console.WriteLine(res.ToString());
}
another thing that i should say i add this permissions to manifest <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET" />
I connected the mobile phone to the wireless network ,i mean the mobile can access my ip .
The problem is the gps data is generated so slowly i don't know why ?another problem is the android application doesn't send any data to server ,
Client
To accelerate the location update, you have to specify to the Activity the location update interval when setting the LocationListener implementation.
Something like :
LocationListener impl = new MyLocationListenerImpl();
long interval = 4000;//change your code here
setLocationListener(impl, interval);
(Note that the code above is more like a pseudo code, since It's been a long time since I have touched LocationListener).
Server
The code you provided does not mention the "OnDataReceived" member function. So I think that you should dig in this way.
Unless sockets are used on purpose, consider using Http Protocol and frameworks like ASP.NET and loopj Async Http to pass data to a server, it's easier !
How can I check if a UNC Path is available?
I have the problem that the check takes about half a minute if the share is not available :
var fi = new DirectoryInfo(#"\\hostname\samba-sharename\directory");
if (fi.Exists)
//...
Is there a faster way to check if a folder is available?
I'm using Windows XP and C#.
How's this for a quick and dirty way to check - run the windows net use command and parse the output for the line with the network path of interest (e.g. \\vault2) and OK. Here's an example of the output:
C:\>net use
New connections will be remembered.
Status Local Remote Network
-------------------------------------------------------------------------------
OK O: \\smarty\Data Microsoft Windows Network
Disconnected P: \\dummy\Data Microsoft Windows Network
OK \\vault2\vault2 Microsoft Windows Network
The command completed successfully.
It's not a very .netish solution, but it's very fast, and sometimes that matters more :-).
And here's the code to do it (and LINQPad tells me that it only takes 150ms, so that's nice)
void Main()
{
bool available = QuickBestGuessAboutAccessibilityOfNetworkPath(#"\\vault2\vault2\dir1\dir2");
Console.WriteLine(available);
}
public static bool QuickBestGuessAboutAccessibilityOfNetworkPath(string path)
{
if (string.IsNullOrEmpty(path)) return false;
string pathRoot = Path.GetPathRoot(path);
if (string.IsNullOrEmpty(pathRoot)) return false;
ProcessStartInfo pinfo = new ProcessStartInfo("net", "use");
pinfo.CreateNoWindow = true;
pinfo.RedirectStandardOutput = true;
pinfo.UseShellExecute = false;
string output;
using (Process p = Process.Start(pinfo)) {
output = p.StandardOutput.ReadToEnd();
}
foreach (string line in output.Split('\n'))
{
if (line.Contains(pathRoot) && line.Contains("OK"))
{
return true; // shareIsProbablyConnected
}
}
return false;
}
Or you could probably go the route of using WMI, as alluded to in this answer to How to ensure network drives are connected for an application?
In my project I use the System.IO :
if (Directory.Exists(#"\\hostname\samba-sharename\directory")) { ...
and it's pretty fast so far...
In a project of mine, i had to check whether a server connection was established or not. I used a TCP Socket to asynchronically check whether the server could be reached or not. I wonder if you could use this to check on a network share. The async TCP Socket connect goes so fast i tested for the connection 10 times under 60 miliseconds. Maybe you could play around with that a bit ?
EDIT: Here is the Asynchronous Socket i used for my project. Use this class to check for a certain IP or address. Hope it is of any use to you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace Base.BaseObjects
{
public class AsynchronousClient
{
#region Properties
private int _port = 0000, currentTry = 0, _buffersize, _fastpingdelay = 80;
private string _server = "localhost";
private Socket client;
private static IPEndPoint remoteEP;
// Delegates & Events
public delegate void SendMessageDelegate(string message);
public event SendMessageDelegate SendMessageEvent;
public delegate void ConnectionStatusDelegate(bool connected, bool reconnect);
public event ConnectionStatusDelegate ConnectionStatusChanged;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
/// <summary>
/// Port to monitor
/// </summary>
public int Port { get { return _port; } }
/// <summary>
/// Number of packages to buffer until system reports connection loss
/// </summary>
public int BufferSize { get { return _buffersize; } }
/// <summary>
/// Time in milliseconds between two pings
/// </summary>
public int FastPingDelay { get { return _fastpingdelay; } }
/// <summary>
/// Servername to connect to
/// </summary>
public string Server
{
get { return _server; }
set
{
_server = value;
// Resolve the remote endpoint for the socket.
try
{
IPAddress ipAddress = (IPAddress)Dns.GetHostAddresses(value)[0];
remoteEP = new IPEndPoint(ipAddress, Port);
}
catch (SocketException ex)
{
SendMessage(ex.Message);
}
}
}
#endregion
#region Events & Delegates
protected void SendMessage(string message)
{
if (SendMessageEvent != null)
SendMessageEvent(message);
}
protected void UpdateConnectionStatus(bool connected, bool reconnect)
{
if (ConnectionStatusChanged != null)
ConnectionStatusChanged(connected, reconnect);
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
SendMessage(String.Format("Socket connected to {0}", client.RemoteEndPoint.ToString()));
//UpdateConnectionStatus(true, false);
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
SendMessage(e.ToString());
UpdateConnectionStatus(false, true);
}
}
#endregion
#region methods
public AsynchronousClient(int port, string server)
{
_port = port;
Server = server;
_buffersize = 10;
_fastpingdelay = 20;
}
public void CreateSocket()
{
try
{
StopClient();
}
catch (Exception ex)
{
SendMessage(ex.Message);
}
finally
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
}
public bool FastPingSocket()
{
for (currentTry = 0; currentTry <= BufferSize; currentTry++)
{
try
{
CreateSocket();
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
System.Threading.Thread.Sleep(FastPingDelay);
client.Shutdown(SocketShutdown.Receive);
connectDone.WaitOne();
client.Close();
return true;
}
catch (SocketException ex)
{
SendMessage(ex.Message);
}
catch (ObjectDisposedException ex)
{
currentTry--;
SendMessage(ex.Message);
CreateSocket();
}
catch (NullReferenceException ex)
{
currentTry--;
SendMessage(ex.Message);
CreateSocket();
}
catch (ArgumentNullException ex)
{
SendMessage(ex.Message);
CreateSocket();
}
catch (InvalidOperationException ex)
{
SendMessage(ex.Message);
CreateSocket();
currentTry--;
}
finally
{
StopClient();
}
}
UpdateConnectionStatus(false, true);
return false;
}
public void StopClient()
{
// Release the socket.
try
{
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception) { }
finally
{
UpdateConnectionStatus(false, false);
}
}
#endregion
}
}
Edit: Please don't just copy/paste it. Try to understand the code so you can use it for your benefit, and finetune it for your needs.
I ended up "cheating" and just pinging the host, which is reasonable as that in reality is the case that I'm checking for.
private bool HostExists(string PCName)
{
Ping pinger = new Ping();
try
{
PingReply reply = pinger.Send(PCName);
return reply.Status == IPStatus.Success;
}
catch
{
return false;
}
finally
{
pinger.Dispose();
}
}
This way suits me best because of its speed, simplicity, and reliability.
I used the ping method suggested above and it did not work for me since I am using OpenDNS
Here is a function that worked well for me:
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/// <summary>
/// A quick method to test is the path exists
/// </summary>
/// <param name="s"></param>
/// <param name="timeOutMs"></param>
/// <returns></returns>
public static bool CheckPathExists(string s, int timeOutMs = 120) {
if (s.StartsWith(#"\\")) {
Uri uri = new Uri(s);
if (uri.Segments.Length == 0 || string.IsNullOrWhiteSpace(uri.Host))
return false;
if (uri.Host != Dns.GetHostName()) {
WebRequest request;
WebResponse response;
request = WebRequest.Create(uri);
request.Method = "HEAD";
request.Timeout = timeOutMs;
try {
response = request.GetResponse();
} catch (Exception ex) {
return false;
}
return response.ContentLength > 0;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Do a Ping to see if the server is there
// This method doesn't work well using OPenDNS since it always succeeds
// regardless if the IP is a valid or not
// OpenDns always maps every host to an IP. If the host is not valid the
// OpenDNS will map it to 67.215.65.132
/* Example:
C:\>ping xxx
Pinging xxx.RT-AC66R [67.215.65.132] with 32 bytes of data:
Reply from 67.215.65.132: bytes=32 time=24ms TTL=55
*/
//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 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
//byte[] buffer = Encoding.ASCII.GetBytes(data);
//int timeout = 120;
//PingReply reply = pingSender.Send(uri.Host, timeout, buffer, options);
//if (reply == null || reply.Status != IPStatus.Success)
// return false;
}
}
return File.Exists(s);
}
Thats probably the quickest way, the delay will be the general network speed/disk access etc.
If this is causing a delay for the user, you could try checking this asynchronously?
Maybe you should try to create the folder, if it does exist, it will return an error that you could catch. There should be no default timeout.