I got two Windows UWP Apps. One of them (the "server") is running on a Raspberry Pi 2 on Windows IoT (10586.0). The other (the "client") is running on any Windows 10 device within the same network.
What I want is to get the apps to "talk" to each other. For the moment I just want to send simple String from the client to the server. Later on, serialized data should be transferred trough the network.
This is the code for the server App:
namespace LCARSHomeAutomation
{
/// <summary>
/// Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
try {
EstablishNetworking();
txb_Events.Text += "Server Running";
}catch (Exception ex)
{
txb_Events.Text += ex.Message;
}
}
private async void EstablishNetworking()
{
await StartListener();
}
public async Task StartListener()
{
StreamSocketListener listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnection;
listener.Control.KeepAlive = true;
try
{
await listener.BindServiceNameAsync("5463");
}
catch (Exception ex)
{
if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
//Logs.Add(ex.Message);
txb_Events.Text += ex.Message;
}
}
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Stream inStream = args.Socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(inStream);
string request = await reader.ReadLineAsync();
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// Your UI update code goes here!
txb_Events.Text += (String)request;
});
}
private async Task ConnectSocket()
{
StreamSocket socket = new StreamSocket();
socket.Control.KeepAlive = false;
HostName host = new HostName("localhost");
try
{
await socket.ConnectAsync(host, "5463");
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
string request = "Test Self App \n";
await writer.WriteLineAsync(request);
await writer.FlushAsync();
socket.Dispose();
}
catch (Exception ex)
{
txb_Events.Text += ex.Message;
//Logs.Add(ex.Message)
}
}
private async void btn_Send_Click(object sender, RoutedEventArgs e)
{
await ConnectSocket();
}
}
}
As you can see, I'm establishing a network connection with the same app on the same host and send the string "Test Self App". This works fine for quite some time but after a while I get the Error:
Exception thrown: 'System.Runtime.InteropServices.COMException' in mscorlib.ni.dll
WinRT information: No connection could be made because the target machine actively refused it.
So, this is my first question: What is this Error and how can I fix this?
The other thing is: I'm not able to establish a network Connection between the server and the Client. I don't know, what I am doing wrong. This is the code of the "Client":
namespace LCARSRemote
{
/// <summary>
/// Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void btn_Send_Click(object sender, RoutedEventArgs e)
{
StreamSocket socket = new StreamSocket();
HostName host = new HostName("localhost"); //Replace with coorect hostname when running on RPi
try
{
try {
await socket.ConnectAsync(host, "5463");
}
catch(Exception ex)
{
txb_Events.Text += ex.Message;
}
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
string request = "Remote App Test";
await writer.WriteLineAsync(request);
await writer.FlushAsync();
socket.Dispose();
}
catch (Exception ex)
{
txb_Events.Text += ex.Message;
//Logs.Add(ex.Message)
}
}
}
}
When I click on the btn_Send, I get the error message
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
and
A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
What am I doing wrong? Maybe I should say, that I'm relatively new in programming network connections, sockets etc.
Thanks for any help!
You should try using StreamSocket API in UWP. This sample repo contents both server and client code: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/StreamSocket
A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
This error happened for me when I try to call ConnectAsync twice in a row, I think you can check your logic or debug to confirm in your case.
The first error
Exception thrown: 'System.Runtime.InteropServices.COMException' in
mscorlib.ni.dll
WinRT information: No connection could be made because the target
machine actively refused it.
This is because the socket is still open with a previous request and has not closed yet. So catch this error and try and to reconnect.
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond.
This is because the server and client are on the same machine, I a running into this same problem supposedly you can run from an elevated command prompt
checknetisolation loopbackexempt -d -n= {package family}
to resolve it.
This solution did not work for me. So your server must run on a pi and client must run on your desktop PC for windows 10 UWP to be able to connect to it.
Windows 10 does not allow loopback connection for UWP applications as far as I can tell.
If you truly want to run a socket server/web server node.js windows universal apps might be a good approach
https://ms-iot.github.io/content/en-US/win10/samples/NodejsWU.htm
or
RestUP https://github.com/tomkuijsten/restup
Depending how much data you're talking about and what the end use case is, Amazon's AWS IoT Platform might be something to look at. It's pretty cool for a number of reasons. Specifically I like that the target device can be offline at the time of transmission.
It's free (250,000 messages) for the first year and $5 per one million messages after that. Every 512 byte block counts as 1 message credit.
Related
I'm using UdpClient to receive data from a single host(actually it's a microcontroller that sends 32 bytes of data every 4 milliseconds.
The program I wrote is pretty simple.
I'm initializing the UdpClient like this(in Program.cs):
public static UdpClient client = new UdpClient(1414);
after that i do this in Form_Load event:
static UdpClient client = Program.client;
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
and then call the client.Recieve() like this:
Task.Run(() =>
{
while (true)
{
try
{
data = client.Receive(ref RemoteIpEndPoint);
}
catch (Exception ex)
{
String err_type = ex.GetType().Name;
if (err_type == "SocketException")
{
MessageBox.Show("Cannot Find The Device.", "Device Error.");
}
}
}
});
the program runs fine on my own system (using Windows 10). However when i run this program on windows 7,at random times,but with 100% chance client.Recieve() stops working and the program no longer receives any data. no exception is thrown. to find the root of the problem, I installed Wireshark to test if there is any incoming data.The answer was no(the LAN port light stops blinking too) . What has me confused is that this does not happen on windows 10.
The thing is, you miss all exceptions except SocketException.
To find out, what's going on, please, rewrite your catch block:
Task.Run(() =>
{
while (true)
{
try
{
data = client.Receive(ref RemoteIpEndPoint);
}
catch (SocketException ex)
{
MessageBox.Show("Cannot Find The Device.", "Device Error.");
}
catch (Exception e)
{
MessageBox.Show(e.GetType().Name, e.Message);
}
}
});
Turns out my code was completely fine.
This was a hardware problem on our side.
We are creating application to communicat external device with windows PC (here we are using windows 7), in PC we are using bluetooth dongle.
when we tried to discover and pair device it was successfull in windows PC.
But in code side we are trying to connect the device it was not successfull and here we are using 32feet.net to connect the device.
below code i am trying to connect the device.
////_serviceClassId = new Guid("9bde4762-89a6-418e-bacf-fcd82f1e0677");
Guid serviceClass = BluetoothService.RFCommProtocol;
int selectedIndex = device_list.SelectedIndex;
BluetoothDeviceInfo selectedDevice = this.array[selectedIndex];
var lsnr = new BluetoothListener(serviceClass);
lsnr.Start();
Task.Run(() => Listener(lsnr));
and the Listener method is
private void Listener(BluetoothListener lsnr)
{
try
{
while (true)
{
using (var client = lsnr.AcceptBluetoothClient())
{
using (var streamReader = new StreamReader(client.GetStream()))
{
try
{
var content = streamReader.ReadToEnd();
if (!string.IsNullOrEmpty(content))
{
////_responseAction(content);
}
}
catch (IOException)
{
client.Close();
break;
}
}
}
}
}
catch (Exception exception)
{
// todo handle the exception
// for the sample it will be ignored
}
}
If i run the application it will blocked in the lsnr.AcceptBluetoothClient() Can any one help what wrong in this?
Note : Bluetooth device created two comports one is incoming and anther one is outgoing port, when we connect through PC.
It is because it wait untill it have a client connected. You have to run it in a thread to work simultaneously!
Hey, I have a Problem with the Windows 10 UWP API.
I'm developing a Windows 10 UWP App and need to connect to a Chromecast. I'm using SharpCaster for this. But when I open a connection to a Chromecast and close it again later on, it is not possible to connect to a Chromecast again. The socket to the Chromecast opens again, but when trying to write to it, I get the following exception:
A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
This even happens when I turn the Chromecast off while disconnected. I disconnect the Chromecast with this Method:
public void Disconnect()
{
_running = false;
_socket.InputStream.Dispose();
_socket.OutputStream.Dispose();
_socket.Dispose();
}
The method is not found in the Library, I have written it myself. Setting _running to false stops all the loops for pinging, etc...
The socket is created with this code:
_socket = new StreamSocket().ConfigureForChromecast();
await _socket.ConnectAsync(new HostName(uri.Host), ChromecastPort, SocketProtectionLevel.Tls10);
The extension ConfigureForChromecast() looks like this:
public static StreamSocket ConfigureForChromecast(this StreamSocket socket)
{
//Chromecast is not using trusted certificate so ignoring errors caused by that
socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
socket.Control.OutboundBufferSizeInBytes = 2048;
socket.Control.KeepAlive = true;
socket.Control.QualityOfService = SocketQualityOfService.LowLatency;
return socket;
}
Finally, the messages are written to the socket with
internal async Task Write(byte[] bytes)
{
try
{
var buffer = CryptographicBuffer.CreateFromByteArray(bytes);
await _socket.OutputStream.WriteAsync(buffer);
}
catch (Exception e)
{
Debugger.Break();
}
}
And that is the point where the exception occurs. When connecting the first time, it works perfectly, but to connect a second time, I have to restart the whole app. Any ideas why?
the problem: While not using a VPN, the code below works fine. As soon as I connect to my home network via a VPN the, code throws an exception (translated from german):
A connection attempt failed because the connected party did not properly respond after a certain period of time, or established connection failed because connected host has failed to respond. (Exception from HRESULT: 0x8007274C).
The target "192.168.180.58" is an another computer within my home network.
Windows Store test code:
private async void createConnection(object sender, RoutedEventArgs e)
{
HostName target = new HostName("192.168.180.58");
string port = "8181";
using (StreamSocket client = new StreamSocket())
{
try
{
await client.ConnectAsync(target, port);
}
catch (Exception ex)
{
string typeName = ex.GetType().Name;
string msg = ex.Message;
}
}
}
I created a Windows Console Program (.NET 4.5.1) that is working in both situations (connected by using vpn and not using a vpn).
Windows Console test code:
namespace caPing
{
class Program
{
static void Main(string[] args)
{
string target = "192.168.180.58";
int port = 8181;
TcpClient client = new TcpClient();
try
{
client.Connect(target, port);
client.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
It looks like that the problem is somehow related to the execution environment for Windows Store Apps (when using a vpn).
What is the problem here and how can I solve it?
Kind regards,
Sörnt
I was facing the same problem then i found that
We can not keep two app running at the same time.
If Server app is running and then run the client app, the server app will
suspend and the client app will fail with connect.
You can create a server application as a desktop app, so that the client and
server can run at the same time.
From MSDN Here.
I have a Visual Studio 2008 C# .NET 3.5 application running on Windows XP SP3 x86. In my application, I have an event handler OnSendTask that can be called by multiple threads simultaneously. It opens a TCP connection to a remote host and sends/receives data.
For example:
/// <summary>
/// prevent us from exceeding the maximum number of half-open TCP
/// connections in Windows XP.
/// </summary>
private System.Threading.Semaphore tcp_connection_lock_ =
new System.Threading.Semaphore(10, 10);
public event EventHandler<SendTaskEventArgs> SendTask;
private void OnSendTask(object sender, SendTaskEventArgs args)
{
try
{
tcp_connection_lock_.WaitOne();
using (TcpClient recipient = new TcpClient())
{
// error here!
recipient.Connect(args.IPAddress, args.Port);
using (NetworkStream stream = recipient.GetStream())
{
// read/write data
}
}
catch
{
// write exceptions to the logfile
}
finally
{
tcp_connection_lock_.Release();
}
}
void SendTasks(int tasks_to_send)
{
using (ManualResetEvent done_event = new ManualResetEvent(false))
{
int countdown = tasks_to_send;
for (int i = 0; i < tasks_to_send; ++i)
{
ThreadPool.QueueUserWorkItem((o) =>
{
SendTaskEventArgs args = new SendTaskEventArgs(/*...*/);
EventHandler<SendTaskEventArgs> evt = SendTask;
if (evt != null)
evt(this, e);
if (Interlocked.Decrement(ref countdown) == 0)
done_event.Set();
}, i);
}
done_event.WaitOne();
}
}
Unfortunately, I occasionally see this error:
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.0.16:59596
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
Some points of information:
If I send a task to 40 remotes, I will see this response from around 6.
A Wireshark trace shows no attempt to even initiate a TCP connection from the PC to the remote.
I can ping the remote from the PC and get consistent good responses.
The remotes are all on the same switch and subnet as the PC running this application. There is no fancy networking in the way.
Can anybody suggest what may be causing this error or how I can fix it?
Thanks
I am not sure of all of the details behind the max half-open TCP connections but, I believe it is NOT specific to application connections, but rather system wide. Are you sure that when this error occurs there are no other applications on the system that are creating TCP connections?
I'd setup a retry whenever an error occurs. Something like:
private const int MaxRetries = 10;
private void OnSendTask(object sender, SendTaskEventArgs args)
{
bool retry = false;
try
{
tcp_connection_lock_.WaitOne();
using (TcpClient recipient = new TcpClient())
{
// error here!
recipient.Connect(args.IPAddress, args.Port);
using (NetworkStream stream = recipient.GetStream())
{
// read/write data
}
}
}
catch (SocketException ex)
{
if(args.RetryCount < MaxRetries)
{
retry = true;
args.RetryCount++;
}
else
{
// write exceptions to the logfile
}
}
finally
{
tcp_connection_lock_.Release();
}
if(retry)
{
Thread.Sleep(1);
OnSendTask(sender, args);
}
}