I try to communicate using a simple TCP client server on UWP, I followed this link UWP socket but it looks like it doesn't works. I've added capabilities for both app to provide client & server. Even if it doesn't appear in the code, I have handled the error, which give me the following : System.Runtime.InteropServices.COMException (0x8007274C): A connection attemps has failed because the connected part has not answer after a certain amount of time or the connection has failed because host has not respond
System.Runtime.InteropServices.COMException (0x8007274C): Une tentative de connexion a échoué car le parti connecté n’a pas répondu convenablement au-delà d’une certaine durée ou une connexion établie a échoué car l’hôte de connexion n’a pas répondu.
As far I can look, it fails at the line await clientSocket.ConnectAsync(serverHost, serverPort);
At term, it should run the server on a Rasperry Pi 3 and the Client on a Windows 10 mobile (Lumia 950 XL build 14385) but until now I only terted on a surface pro 3 running Windows 10 Pro (build 14385)
Client
try
{
StreamSocket clientSocket;
clientSocket = new StreamSocket();
HostName serverHost = new HostName("localhost");
string serverPort = "5464";
await clientSocket.ConnectAsync(serverHost, serverPort);
Stream streamOut = clientSoket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
string request = "test";
await writer.WriteLineAsync(request);
await writer.FlushAsync();
Stream streamIn = clientSocket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string response = await reader.ReadLineAsync();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());//handle
}
Server
try
{
serverSocket = new StreamSocketListener();
serverSocket.ConnectionReceived += ServerSocket_ConnectionReceived;
await serverSocket.BindServiceNameAsync("5464");
}
catch(Exception e)
{
Console.WriteLine(e.ToString());//handle
}
private async void ServerSocket_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Stream inputStream = args.Socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(inputStream);
string request = await reader.ReadLineAsync();
Stream outputStream = args.Socket.OutputStream.AsStreamForWrite();
StreamWriter writter = new StreamWriter(outputStream);
await writter.WriteLineAsync("Ok");
await writter.FlushAsync();
}
After some research and thanks to Stuart Smith, It appears that two apps cannot directly connect between each other. For developement purposes, it could be allowed on a local machine, using a tool to enable network loopback. When I tried to run the client on my lumia and the server on my PC, it worked perfectly.
Here are the link used to understand this.
StackOverFlow UWP Enable loopback
Using network loopback in side-loaded Windows Store apps
Related
I have this code which works fine for project type of Console App (.NET Core).
class Program
{
static void Main(string[] args)
{
var L = new TcpListener(IPAddress.Any, 4994);
L.Start();
using (var C = L.AcceptTcpClientAsync().Result)
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is from Console!!!");
Console.WriteLine(BR.ReadString());
}
}
}
But when I use this code in project type of Blank App (Universal Windows) like this:
public MainPage()
{
InitializeComponent();
ThreadPool.RunAsync(foo);
}
static void foo(IAsyncAction operation)
{
var L = new TcpListener(IPAddress.Any, 4994);
L.Start();
using (var C = L.AcceptTcpClientAsync().Result)
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is from UWP!!!");
Debug.Write(BR.ReadString());
}
}
It will listen to that port when I check it by netstat but when the client wants to connect this exception will be thrown.
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'
The UWP App has Private Networks (Client & Server) and Internet (Client & Server) capabilities.
Turning firewall on and off didn't help.
Target Version: Windows 10 Creators Update (10.0; Build 15063)
Client Code which is a WPF application:
using (var C = new TcpClient("127.0.0.1", 4994))
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is a test");
MessageBox.Show(BR.ReadString());
}
Debugging UWP & TCP listeners from localhost has always been problematic. Your code is OK and it should work if you try to connect into it from an external computer. The issue you're seeing is quite likely a bug/hyper-v issue/networking problem in the network isolation.
You can check if the network isolation for your app is enabled (it is by default) running the following from command prompt:
CheckNetIsolation.exe LoopbackExempt -s
My recommendation is to use an external computer to make sure that your code is fine (it should be). After that you can try to fight with the network isolation but that can be frustrating.
Here's an another issue where this has been discussed: Unable to access TCP Server inside a Windows Universal Application
I wanted to transmit an array over Bluetooth using Windows Phone 8, so I referred to the following intro guide on MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/jj207007(v=vs.105).aspx
Pairing/Connecting was pretty straightforward and when I deployed the app to my Lumia 620 I was able to see my paired HTC Desire using the sample code in the above. So next I tried sending a basic 5-byte array using the following code:
async void BLEfunc()
{
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var peers = await PeerFinder.FindAllPeersAsync();
if (peers.Count == 0)
{
Details.Text = "No Device Found";
}
else
{
PeerInformation selectedPeers = peers[0];
StreamSocket socket = new StreamSocket();
await socket.ConnectAsync(selectedPeers.HostName, "1");
Details.Text = "Connected to device: " + selectedPeers.DisplayName; //Details is a TextBlock on screen
using (var dataWriter = new DataWriter(socket.OutputStream))
{
//byte[] DataArray = { 1, 2, 3, 4, 5 };
dataWriter.WriteByte(1);
var result = await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
Details.Text = "Data sent!";
}
}
The problem is that the program runs into an unhandled exception when it enters the using code block in the above pasted code. Everything up to that point runs fine. I got the idea for the above code from here: Sending files via bluetooth from winRT to android / WP devices
Any ideas?
Hey i was wondering if you could help me
I'm creating an android application in html5 and java script.
There are a server that is created on c# that is listing connection.
I can connect the 2 apps together but get i can get the c# app to reply to my android application using javascript.
here is my server code
public void Listeners()
{
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
nr_connections = nr_connections + 1;
nr_qry = nr_qry + 1;
SetText("");
SetText("New Connection.");
NetworkStream networkStream = new NetworkStream(socketForClient);
StreamWriter streamWriter = new StreamWriter(networkStream);
StreamReader streamReader = new StreamReader(networkStream);
streamWriter.Flush();
string GettheString = streamReader.ReadLine();
if (GettheString == "server_status")
{
SetText("Checking Server Status.");
streamWriter.WriteLine("Online");
streamWriter.Close();
streamReader.Close();
networkStream.Close();
}
}
socketForClient.Close();
SetText("Connection Closed...");
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
nr_connections = nr_connections - 1;
}
and my javascript code
function connect ()
{
try
{
var connection = new WebSocket('ws://105.237.125.247:8');
connection.onopen = function ()
{
connection.send('server_status');
};
connection.onmessage = function (event) {
alert(event.data);
}
}
catch(Exeption)
{
alert("Check Connection");
}
}
Im getting data from the android app but can send back to the javascript file
Web-sockets is a protocol that sits on top of a regular transport (such as a socket); basically, you need a web-socket library. If you are using recent versions of Windows, then much of this is baked into HTTP.SYS, and available via HttpListnener (in particular, AcceptWebSocketAsync on a context). However, alternative web-socket libraries are available, or can be written from scratch if you so choose.
i have done a server using this example socketAsyncEventArgs
in visual studio 2010 and .net 4.0.
Now i'm trying to connect to it from a windows 8 app using StreamSocket but i'm getting a "Acces denied" message.
here is the Client code:
private StreamSocket streamSocket;
public string Server = "192.168.0.101";
public int Port = 9900;
public async void Connect()
{
streamSocket = new StreamSocket();
Connect();
try
{
await streamSocket.ConnectAsync(
new Windows.Networking.HostName(Server),
Port.ToString()); // getting Acces Denied here
DataReader reader = new DataReader(streamSocket.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
while (true)
{
var bytesAvailable = await reader.LoadAsync(1000);
var byteArray = new byte[bytesAvailable];
reader.ReadBytes(byteArray);
}
}
catch (Exception e)
{
MessageBox(e.StackTrace);
}
}
How to fix the problem? Is there another way to send and receive messages using this server?
You are probably also seeing the following as part of your error message:
WinRT information: A network capability is required to access this network resource
This is because you need to add a capability to your application that allows you to access local networks. Double click on the Package.appxmanifest file in your project. Click on the Capabilities tab. Add the Private Networks (Client & Server) capability to your project.
I'm trying to understand how SSL works. In my wish to make a small FTP client which supports SSL I've run into some problems:
TcpClient FtpConnection = new TcpClient(FtpServer, FtpPort);
NetworkStream FtpStream = FtpConnection.GetStream();
StreamReader FtpReader = new StreamReader(FtpStream);
FtpWriter = new StreamWriter(IrcStream);
send_cmd("AUTH SSL");
send_cmd is just a FtpWriter.WriteLine(text); FtpWriter.Flush(); function.
My "problem" is this: First I need to make a (non-ssl) connection to the FTP, then tell it to do a ssl connection (AUTH SSL), and I would guess I then need to make a new connection - something like:
TcpClient client = new TcpClient(FtpServer, FtpPort);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient("foobar");
}
catch (AuthenticationException e)
{
MessageBox.Show("Authentication failed - closing the connection.");
client.Close();
return;
}
Taken from msdn.
I keep dying on handshake failed due to unexpected packet format (which I've tried googling, but all say it's because the author has connected to a wrong port), which I take as: The connection is not ssl until AUTH SSL is send to it. So my question is, how would i go about making this a "hybrid" connection so I can make an SSL connection to the server?
Any help is greatly appreciated!
Using a library like that is the opposite of what I wanted. Since I found so few hits when searching the web, I'll post what I figured out:
Building a C# ftp client is basically like so:
TcpClient blabla = new TcpClient("some.host", 21);
NetworkStream blabla_stream = blabla.GetStream();
StreamReader unsecure_reader = new StreamReader(blabla_stream);
StreamWriter blabla_writer = new StreamWriter(blabla_stream);
blabla_writer.WriteLine("AUTH SSL");
string response = "";
while ((response = unsecure_reader.ReadLine()) != null)
{
if (response.Substring(0,3) == "234")
{
SslStream ssl_connection = new SslStream(blabla.GetStream(), false, new RemoteCertificateValidationCallback(validate_certificate), null);
ssl_connection.AuthenticateAsClient("");
StreamReader ssl_stream = new StreamReader(ssl_connection);
ftp_writer = new StreamWriter(ssl_connection);
}
}
where validate_certificate is a function based on msdn's (you can google it and mod it easily yourself).
For more info see RFC 4217 and 2228.
http://ftps.codeplex.com/
This project contains every pieces you need.