Multicast Socket Not Receiving After Disabling/Enabling Network Connection - c#

I'm using Socket with following configuration to receive multicast packets and the code is working properly.
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(bindPoint);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, IPAddress.Any));
socket.ReceiveTimeout = 1000;
But after disabling the network connection from Control Panel and enabling, the socket cannot receive the multicast data. I can see the packets with Wireshark. I tried closing the socket, resetting he socket but restarting is the only solution I came up with. The application will be used in an environment where the user typically remove the ethernet cable and plug another one.
Initially I was using UdpClient but the same problem persists on that too. The operating system is Windows 7 and I use .NET 4.5.2.

After disabling a network connection, Windows automatically uses another connection if you have one (virtual host etc.). After enabling the previous connection, the application doesn't use the correct connection since there were no interface selection made. Disabling other connections or specifying the interface solves the problem.

Related

UDP for interprocess communication

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.
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.

Server Client Application with .NET and Xamarin

I searched around the internet a lot of hours but I couldn't find anything that matches my case.
I simply want to implement a Server/Client App with TCP or UDP where my Android App (Xamarin) acts as a server and my .NET application as Client. Since I have not much experience with app development and no experience with Xamarin, I was looking for an example. All I found was this:
http://www.codeproject.com/Articles/340714/Android-How-to-communicate-with-NET-application-vi
First of all this is the opposite way (Server on .NET and Client as App) and additionaly it is for Android Studio so it's hard for me to translate these things into Xamarin without errors.
Please can someone help and give me an example how to realize my issue?
Thank you!
On Xamarin.Android you can use all of the regular .Net socket classes:
Namespaces:
using System.Net;
using System.Net.Sockets;
Example:
IPHostEntry ipHostInfo = Dns.GetHostEntry (Dns.GetHostName ());
IPAddress ipAddress = ipHostInfo.AddressList [0];
IPEndPoint localEndPoint = new IPEndPoint (ipAddress, 11000);
System.Diagnostics.Debug.WriteLine(ipAddress.ToString());
// Create a TCP/IP socket.
Socket listener = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
AndroidManifest.xml Required Permissions are:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
The MSDN-based Asynchronous Server Socket example works as a cut/paste example with no changes.
i.e.
Using the MSDN code, you can call the static method, AsynchronousSocketListener.StartListening, in a thread to start listening on port 11000 defined in the AsynchronousSocketListener class.
new Thread (new ThreadStart (delegate {
AsynchronousSocketListener.StartListening();
})).Start ();
Once it is running on your device/emulator, you can telnet into your Android TCP socket server:
>telnet 10.71.34.100 11000
Trying 10.71.34.100...
Connected to 10.71.34.100.
Escape character is '^]'.
Once connected, type in This is a test<EOF> and the Android will echo it back:
This is a test<EOF>
You do this like in normal .net, except you have to ask permissions to use sockets.
There are tons of simple example of creating a listening tcp connection in c#.
The problem you will have is to know the IP address of your server (in the phone) as it will likely change often when the user is moving.

synchronous multiple socket client clarification

I am going to create multiple synchronous clients . I need some explanation about below code.
When i am creating a socket like below and call connect what is happening at network level.
I believe when we create a socket and call connect, a TCP/IP connection a tunnel made between client socket and server socket.
Once this sender(socket) connect with server ,that client & server will have a unique tunnel between them.
if i create another client it will have another unique tunnel between them.
In case if we got an error, that the client is not connected, always we should reconnect using existing socket(sender) then we will access the same data/connection that we had.
And we should not create a new socket then we will have a new tunnel and we will lost the previous connection and data.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
sender.Connect(remoteEndpoint)
Please clarify if i am wrong.
What you call tunnel is really called a connection. Broken connections cannot be revived. Data loss is to be expected.
When you reuse an existing socket object to connect again you are creating a new connection. Reusing socket objects is not recommended (by me) because it is confusing.
Note, that TCP does not know what a socket is. The spec does not contain that word. Sockets are OS-level things.

A service that makes tcp connections to multiple clients

Most of the examples online are examples of a multithreaded tcp server, whereby the server listens for multiple incoming connections from the client.
What I'm looking for is for the "server", to initiate the connections. If I have 100 devices (all different IP address of course), my server will have to make 100 individual connections to each device and receive data from the devices.
This is how I would make my connection to a device
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
_socket.SendTimeout = 2000;
_socket.ReceiveTimeout = 2000;
_socket.Connect(new IPEndPoint(IPAddress, TCPPort));
But I would like to know if there's any component out there, that would fulfill the following
establish as many tcp connections as I want to the devices
receive & send data through the connection
handle tcp timeouts/disconnects/etc & re-establish connection to the IP
If there aren't any of such components, are there any tips as to how I should go about doing it? e.g., 1 connection per thread, or how do I handle if the data is received in multiple packets, etc?
Any insights would be greatly appreciated
There are several existing components out there that you could use to achieve what you want. Checkout http://www.networkcomms.net and http://code.google.com/p/lidgren-network-gen3/.
Having said that people always prefer to add that there is nothing stopping you writing everything from scratch yourself as per the example you give.
Disclaimer: I'm a developer for NetworkComms.Net.

Uniting TCP and UDP in C#

So ideally, I am looking for a way to unite TCP and UDP on the server and manage both these connections under individual client threads. Currently, I am wondering if it is possible to accept a TCP connection and set up UDP communication from that.
Here is my ideal setup:
Client connects on TCP to server via TCPClient.connect()
Server accepts TCP connection via TCPListener
when server accepts TCP connection, it also gets the IPEndpoint from the TCP connection
and uses that to begin UDP communcation with:
serverUDPSocket.BeginReceiveFrom (byteData, 0, 1024,
SocketFlags.None, ref (Endpoint)ThatIPEndpointThatIJustMentioned,
new AsyncCallback(client.receiveUDP),
(Endpoint)ThatIPEndpointThatIJustMentioned);
^so this is where I am running into a little bit of a theoretical issue. From my understanding, the endpoints for TCP and UDP would be formatted differently. How can I resolve this issue? I would like to avoid having the client connect to UDP on a separate thread and then uniting these threads under a single managing class.
EDIT:
Here is the code that I am trying to implement:
//Listening for TCP
TcpClient newclient = listenTCP.AcceptTcpClient(); //Accept the client
Client clientr = new Client(newclient); //Create a new Client class to manage the connection
clientr.actionThread = new Thread(clientr.action); //This thread manages the data flow from the client via the TCP stream
clientr.actionThread.Start(clientr);
EndPoint endPoint = newclient.Client.RemoteEndPoint; //so this is the sketchy part. I am trying to get the endpoint from the TCP connection to set up a UDP "connection". I am unsure about the compatibility as UDP and TCP sockets are different.
UDPSocket.BeginReceiveFrom(new byte[1024],0,1024, SocketFlags.None,ref endPoint, new AsyncCallback(clientr.receiveUDP), null); //the AsyncCallBack is like the manager thread for UDP (same as in TCP)
clients.Add(clientr);
There is no problem in creating two listeners in one application, even if they use different protocol. I suppose you are not asking if you can do it on the same port (there is no point to do it anyway).
However listener is consuming thread so it need different thread if there is gui or some process to do in application (for example calculations meanwhile).
If you want to do everything in one thread you must first receive message from first listener, then setup second one. There is no possibility to setup 2 listeners in one thread at the same time because if you setup first listener it will consome whole thread waiting for message.
This was due to a lack of understanding of UDP on my part from the code level.
I ended up setting up the other method I described where it would accept initial UDP packets individually and then direct the communication (EndPoint + Message) towards a managing client class by comparing IP addresses.

Categories