StreamSocket.ConnectAsync throws Exception "HRESULT: 0x8007274C" while using a VPN - c#

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.

Related

How to set a custom connection timeout in 32feet

I am developing code in C# to communicate with a custom Bluetooth device. The code I use to connect to the device essentially looks like this:
BluetoothDeviceInfo device_info = new BluetoothDeviceInfo(BluetoothAddress.Parse(address_str));
try
{
BluetoothClient connection = new BluetoothClient();
connection.Connect(device_info.DeviceAddress, BluetoothService.SerialPort);
if (connection.Connected)
{
...
}
else
{
...
}
}
catch (Exception e)
{
...
}
The problem is that the Connect call often times out after about 5s. Sometimes it succeeds after about 3s and I have reason to believe that a connection could be established successfully if I allowed more time. However, I have nowhere set this timeout of 5s. I just call the Connect method and it times out at some point.
Is there a way to configure this timeout somewhere in 32feet?

BluetoothListener.AcceptBluetooth client blocks in 32Feet windows 7

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!

Windows UWP StreamSocket ReOpen

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?

Network connection with UWP Apps

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.

TcpClient not connecting to remote server

I'm trying to connect to a remote machine using the TcpClient class, but it keeps failing:
An unhandled exception of type 'System.Net.Sockets.SocketException'
occurred in System.dll
Additional information: 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
Testing the code when the client and server are local works, but when I try connecting to a remote machine, it no longer works.
Here is the server code:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WebSocketServer
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting a new WebSockets server.");
WebSocketServer server = new WebSocketServer();
Console.WriteLine("The WebSocket server has started.");
bool userRequestedShutdown = false;
while (!userRequestedShutdown)
{
Console.ReadLine();
DialogResult result = MessageBox.Show("Do you want to shut the server down?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
userRequestedShutdown = true;
}
}
server.Stop();
}
class WebSocketServer
{
TcpListener server;
Thread connectionListener;
ConcurrentDictionary<TcpClient, Thread> clients = new ConcurrentDictionary<TcpClient, Thread>();
public WebSocketServer()
{
server = new TcpListener(IPAddress.Parse("127.0.0.1"), (int)Properties.Settings.Default["Port"]);
try
{
server.Start();
}
catch (Exception exception)
{
Console.WriteLine("Error while trying to start the server: {0}", exception.ToString());
}
connectionListener = new Thread(() =>
{
while (true)
{
Console.WriteLine("Waiting for a new client.");
try
{
TcpClient client = server.AcceptTcpClient();
Thread clientListener = new Thread(() =>
{
try
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
Console.WriteLine("Wating for the client to write.");
while (client.Connected)
{
try
{
int bytesRead = stream.Read(buffer, 0, buffer.Length);
Console.WriteLine("Read {0} bytes from the client.", bytesRead);
string data = Encoding.UTF8.GetString(buffer).Substring(0, bytesRead);
Console.WriteLine("Read the following string from the client: {0}", data);
}
catch (Exception exception)
{
Console.WriteLine("Error while trying to read from a TCP client: {0}", exception.ToString());
break;
}
}
Console.WriteLine("Client disconnected. Removing client.");
}
catch (Exception exception)
{
Console.WriteLine("Error while trying to connect to a TCP client: {0}", exception.ToString());
}
client.Close();
clients.TryRemove(client, out clientListener);
});
clientListener.Start();
clients.TryAdd(client, clientListener);
}
catch (Exception exception)
{
Console.WriteLine("Error while trying to accept a TCP client: {0}", exception.ToString());
}
Console.WriteLine("A client has connected.");
}
});
connectionListener.Start();
}
public void Stop()
{
server.Stop();
connectionListener.Abort();
}
}
}
}
Here is the client code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketClient
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Opening up a TcpClient.");
TcpClient client = new TcpClient();
client.Connect("<Remote Hostname>", <RemotePortNumber>);
Console.WriteLine("TcpClient has connected.");
NetworkStream stream = client.GetStream();
bool closed = false;
new Thread(() =>
{
while (!closed)
{
Console.WriteLine("Writing data to the stream.");
byte[] bytes = Encoding.UTF8.GetBytes("Hello, world.");
stream.Write(bytes, 0, bytes.Length);
Thread.Sleep(1000);
}
}).Start();
Console.ReadLine();
closed = true;
}
}
}
So what is the problem here? I am hosting the server on an Azure Virtual Machine, I have opened up the TCP port I am trying to use as the <RemotePortNumber> in Windows Firewall on my remote server by setting both inbound and outbound rules to allow all traffic in and out of the machine on that port, and I have created a TCP endpoint on my Azure portal that maps the external port of my Virtual Machine's hostname to the internal, private port, of my Virtual Machine, both set to map the same port number of <RemotePortNumber> for consistency. To connect, I am using a <Remote Hostname> value of <MyServiceName>.cloudapp.net. I have also tried connecting the stream by using IPAddress.Parse(<Public IP of my Azure Server>) but have had no luck...it just keeps timing out, as if I am not formatting the hostname correctly or something. What am I missing? If anyone can provide some clues as to how to debug the issue, that would also be very helpful.
Update: Running a WireShark trace, I see a lot of these messages (is this bad? I think the TCP Retransmission might be okay if we take into account that for Azure you have to route packets from the public domain's port to the private port of the VM, but not sure about whatever the RST, ACK's are):
Update: Running Microsoft Message Analyzer, I see these messages on the Local Link Layer:
Note: My VM has an Internal IP of 100.75.20.78 and a Public IP of 191.238.37.130. It has the public domain name of ovidius.cloudapp.net. I am trying to host the application on TCP port 6490. I blacked out my personal IP address for the sake of not giving it up.
I have mapped the TCP port in the Azure portal from domain to VM as follows:
After spending two mother _______ days on this (fill in the blanks), I got a little bit creative in ways of exploring alternative methods to try and see if I could rule routing issues out. I can pretty much safely conclude that Microsoft's Virtual Machine routing fails when you map a Public Port to the same Private Port.
For example, I tried setting up the new Socket endpoint below, and it worked because it didn't map the same domain port to the same Virtual Machine port like I had previously done with the WebSocketServer:
Update: Also, when hosting, I had to set up the server, not on the IP of 127.0.0.1, but the Internal IP, which in my case is 100.75.20.78.
Update Again: Contrary to the above solution, I tried to delete the old endpoint at 6490 and recreated it, and it seems to be working when I connect to that address now. I'm not entirely sure why, I can only say that the only difference here is that I had firewall rules on to allow that endpoint's port before creating the endpoint this time...not sure if that would make a difference. I'm honestly not sure what was causing the issues.
Update Yet Again: Just thought about it some more...I think it comes down to the following two issues:
You need to host the server on the Internal IP of your Azure Virtual Machine, not localhost or 127.0.0.1 like I was doing.
You need to not have the "ENABLE DIRECT SERVER RETURN" feature enabled on your Azure endpoint.

Categories

Resources