-1

I currently have 2 .Net applications which run on the same PC simultaneously.

These 2 applications communicate using UDP like this:

Client:

udpUnityToConsole = new UdpClient();
udpUnityToConsole.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
try
{
    udpUnityToConsole.Connect("localhost", 11004);
}

Server:

unityUdpReceive = new UdpClient();
unityUdpReceive.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
unityUdpReceive.Client.Bind(new IPEndPoint(IPAddress.Any, 11004));

The communication stream is fast and reliable, there is just one issue with it and that is that if the PC is not connected to a network then it will crash with a

System.Net.Sockets.SocketException: No such host is known.

If the connection has been established already and then the PC is disconnected from the network, the connection will remain. Only if there is no network connection to start with will it fail.

Any suggestions are greatly appreciated.

slaw
  • 611
  • 2
  • 7
  • 20
  • 1
    Network can fail anytime. Wrap your program with try-catch wherever it is needed. – Tommy Jul 22 '16 at 03:30
  • 1
    If you know that the applications will always run on the same machine, use named pipes. See http://stackoverflow.com/questions/13806153/example-of-named-pipes. That way you don't need a network. But you still should check for errors. – Jim Mischel Jul 22 '16 at 03:38
  • I'm pretty reluctant to change to named pipes at this point. I have a fair bit of code already for the UDP version and I prefer the way UDP works. Anyway I have found an easy solution to my problem. Thanks for the tip – slaw Jul 22 '16 at 03:43
  • Couldn't you use a `try-catch` and infinite `timer` arrangement? where you handle this exception by setting a timer to check at intervals for connectivity? – Ash Jul 22 '16 at 03:59

1 Answers1

0

All I had to do was change localhost to 127.0.0.1 which is the address of the local machine and never changes, therefore it is safe to use. Using localhost meant that the UDP library had to look up the IP being used with the localhost alias, but that wasn't necessary as I knew it already. I could probably also find out the IP some other way and run that query on both applications.

slaw
  • 611
  • 2
  • 7
  • 20