UdpClient does not receive any data in UWP app - c#

I have a UWP app that needs to use UdpClient to receive some data. The code looks very similar to this:
var udp = new UdpClient(port);
var groupEP = new IPEndPoint(IPAddress.Any, port);
while (true)
{
Trace.WriteLine("Waiting for broadcast");
byte[] bytes = udp.Receive(ref groupEP);
Trace.WriteLine($"Received broadcast from {groupEP} :");
Trace.WriteLine($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
}
When I run this code in UWP app it stops at Receive(), does not receive anything, and there are no exceptions.
If I run the same exact code in NET 5 console app everything works fine.
How can I make this code run in UWP app?

A common reason for such kind of network issue is the local network loopback. UWP apps are running in the sandbox and are isolated from the system resources like network and file system. In other works, UWP apps are not allowed to access the local host address by default. Enabling the local network loopback could make UWP apps able to access local network resources.
Please also make sure that you've enabled the enterpriseAuthentication and privateNetworkClientServer capability in the manifest file.

Related

How to debug connection to MQTT server using Xamarin System.Net.Mqtt on Android?

I'm trying to build a simple MQTT application using Xamarin, and testing it on both an Android emulator and a phone. Unfortunately, I'm struggling to make a connection with CreateAsync, and at a loss how to debug it.
I've checked I can connect to my RabbitMQ server as follows:
using System.Net.Mqtt;
Console.WriteLine("Trying to connect...");
var configuration = new MqttConfiguration();
var client = MqttClient.CreateAsync("127.0.0.1", configuration).Result;
var sessionState = await client.ConnectAsync(new MqttClientCredentials(clientId: "test", userName:"mqtt", password:"mqtt"));
Console.WriteLine("...it worked.");
Console.Read();
As the code tells me... it worked. :o) RabbitMQ shows the connection. I tried it with "localhost", the hostname and IP of my PC to check they all work, and an incorrect host name to see what exception gets thrown ("Socketexception: No such host is known").
My troubles start when I try to do this in the actual app. The connection code is fundamentally the same, but run in a separate task as I read you shouldn't do it in the GUI thread:
private async Task<SessionState> Connect(string BrokerHostName, Action<MqttApplicationMessage> publishEventHandler)
{
MqttConfiguration config = new MqttConfiguration();
_client = MqttClient.CreateAsync(BrokerHostName, config).Result;
SessionState sessionState = await _client.ConnectAsync(
new MqttClientCredentials(clientId: Id, userName: "mqtt", password: "mqtt")
);
await _client.SubscribeAsync("common", MqttQualityOfService.AtMostOnce);
_client.MessageStream.Subscribe(publishEventHandler);
return sessionState;
}
Called by:
var task = Connect(BrokerHostName, publishEventHandler);
But nothing happens - the code reaches this line and just hangs. If I set a break, continuing just continues to do nothing. I've made sure the INTERNET and ACCESS_NETWORK_STATE permissions are ticked in the Android manifest (though it makes no apparent difference).
This is what I've tried after some hours of Googling:
Using the hostname or IP address of my PC with the Android device, running with and without debug, and also unplugged from PC and run on its own.
Using 10.0.2.2 and running on the emulator, as I understand this is the equivalent of localhost or 127.0.0.1.
Setting the proxy address on the emulator to the same as my PC and port 1883. Even though the 'Apply' button teases with a "Proxy status: success", it still doesn't connect.
It feels like a networking problem since I can put any old rubbish as the host address and it behaves the same, but I've totally run out of ideas for what to try next or how to see what's going on. Any advice very gratefully received!
I now have this working. Here's the steps I took, in case it helps someone else:
I wrote some test apps to check TCP communication. First a client and server in Windows to check they work, then a Xamarin client app. This worked and proved the network connections were OK.
Installed an MQTT Tester on the Android emulator to prove it was possible to connect to RabbitMQ.
Tried a different MQTT framework: MQTTnet.
Similar problem but different symptoms: the code would get stuck on the .Wait() rather than inside the task itself. Then I removed all the asynchronous code and then it connected.
My conclusion is that the problem may be my lack of understanding of asynchronous programming. System.Net.Mqtt seems to require it while MQTTnet does not, so all's well that ends well!

Xamarin forms IOS socket dosn't connect after restart

My Situation.
Im Building a Xamarin Forms V5.0.0.2291 App. When i deploy this app on my physical device, the following code opens a TCP connection to my PC
do
{
try
{
socket = new Socket(EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
result = socket.BeginConnect(EndPoint, null, null);
success = result.AsyncWaitHandle.WaitOne(10000, true);
if (!socket.Connected)
{
socket.Dispose();
ConnectionLost?.Invoke(this, null);
}
}
catch { }
} while (!socket.Connected);
After i Restart the device and open the App again, it displays a permission popup with "your App" wants to find deviceses in you local network etc....
the code above is wrapped in a while loop and only exits when its truely connected.
I confirm this popup but nothing happends anymore. it cannot establich a connection.
On the IOS Simulator it works without problems but on the physical device it does.
In the Privacy settings my app has the permission granted.
I've already googled a lot but I just can't find anything and I'm slowly running out of ideas..
The concrete Question is:
What do i need do too, to establish a connection even though this code works on Android and IOS simulator perfectly?

play audio from TCP/IP server in UWP client on PI3

I'm trying to make an uwp app which will be a client and will run on PI3. The server is a C# Winforms app, that runs on my Windows 10 computer, which I've found here: https://www.codeproject.com/Articles/482735/TCP-Audio-Streamer-and-Player-Voice-Chat-over-IP. The server can stream audio from microphone device to all the connected clients. Although the project has its own client and I can run both server and client on my local machine. Now I want to build a similar client app in UWP C#. By using the UWP StreamSocketActivity sample, I can connect to the server. But I don't know how to receive the audio data and play it on UWP client. Could anyone give me a hand?
Blow is the screenshot of running server which has one connection from uwp client:
Client connects to the server
Thanks in advance!
As mentioned in the article, the protocol used to transfer the audio data is customized.
Note !!! This is a proprietary project. You can't use my servers or
clients with any other standardized servers or clients. I don't use
standards like RTCP or SDP.
You can find the code in TcpProtocols.cs. In UWP client app, you need to convert the code for UWP. This document shows how to build a basic TCP socket client in UWP. But you also need to modify the code for receive data from server continuously. Following code may be helpful for you.
private async void StartClient()
{
try
{
// Create the StreamSocket and establish a connection to the echo server.
using (var streamSocket = new Windows.Networking.Sockets.StreamSocket())
{
// The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process.
var hostName = new Windows.Networking.HostName(TxtHostName.Text);
await streamSocket.ConnectAsync(hostName, TxtPortNumber.Text);
while(true)
{
using (var reader = new DataReader(streamSocket.InputStream))
{
reader.InputStreamOptions = InputStreamOptions.Partial;
uint numAudioBytes = await reader.LoadAsync(reader.UnconsumedBufferLength);
byte[] audioBytes = new byte[numAudioBytes];
reader.ReadBytes(audioBytes);
//Parse data to RTP packet
audioBytes = Convert_Protocol_LH(audioBytes);
var pcmStream = audioBytes.AsBuffer().AsStream().AsRandomAccessStream();
MediaElementForAudio.SetSource(pcmStream, "audio/x-wav");
MediaElementForAudio.Play();
}
}
}
}
catch (Exception ex)
{
Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
}
}
UPDATE:
RTP Packet
RTSP for living audio is recommended and wide used.The Real Time Streaming Protocol (RTSP) is a network control protocol designed for use in entertainment and communications systems to control streaming media servers. The protocol is used for establishing and controlling media sessions between end points. There are some advantages of RTSP. In this solution, you need to build a RTSP server and then use VLC.MediaElement library or other library which support on Windows IoT Core in your UWP app. But i am not sure this library supports RTP.
In addition, this document shows supported codecs on Windows IoT Core.

Android (C#) -- Service for incoming udp-broadcasts

I'm pretty new to Android programming that's why I need your advice.
Current Situation:
I built an Android application (C#) aswell as a regular Server application (C++) which runs on a Raspberry Pi. Both programs communicate via UDP. At the moment that the Server application receives a signal it sends out a broadcast message which the Android application is listening for. Everything works just fine to the moment that the Android device falls asleep/goes idle which leads to my question.
Question:
How can I accomplish that the Android applications' listener still works, when the device falls asleep? I do not expect any solutions but any kind of advice so I don't waste time with wrong approaches.
Research:
- I read about and tried services that will keep running in the background but the service also stopped as the device went to sleep.
- I read about Broadcast Receivers which allow the application/service to get further information of the system.
- I read about WAKELOCK which allows me to keep the CPU alive, but for my purpose it should be up 'all the time' and that would drain to much energy.
Code that I would like to run in the background:
public void AsyncReceive()
{
// ...
Task.Run(() =>
{
while (this.isActive)
{
byte[] buffer = new byte[1];
DatagramPacket incoming = new DatagramPacket(buffer,
buffer.Length);
try
{
sock.Receive(incoming);
}
catch (...)
{
// Exception handling goes here...
}
// Communicate with the Android application
this.FireBroadCastReceivedEvent();
}
});
}
Edit
I also need to notice the application about incoming messages (#the 'FireBroadCastReceivedEvent()' part of the code). What would be a good way to do that?
I think you must read this link : https://developer.android.com/training/run-background-service/index.html
Hope you find what are you looking for.

How to use StreamSocketListener and StreamSocket in windows 8 Metro App instead of System.Net.Sockets?

I'm Trying to Migrate my existing GChat application, which is a Windows Form App to Windows 8 Metro App.
In the windows forms application i used,
System.Net.Sockets.Socket _socket = new new System.Net.Sockets.Socket();
for enable connection to "talk.google.com".
In MetroApp only StreamSocket and DatagramSockets are available I replaced the Code as suggested in this.
Now I dont know whether the connection is enabled or not. . .
When it step into the code
Windows.Networking.Sockets.StreamSocket sSocket = new Windows.Networking.Sockets.StreamSocket();
sSocket.Controls.KeepAlive = true;
await sSocket.ConnectAsync(hostName,"https");
i got the IP address details but the Connection is not alive when it passes the code, it exits.
if anybody know how to handle the socket conection and enable permanant connection in the background in Metro App, please say me!
Thanks in Advance!
Start with StreamSocket sample. This may be helpful.

Categories

Resources