Windows 8 app how to connect to Socket server - c#

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.

Related

FTP Connection issue- using FluentFTP for port 990 -TLS

I am trying download file through FTPS connection with port 990 (TLS) using FluentFTP.
But the code is not able to establish connection and showing exception as "The remote certificate is invalid according to the validation procedure."
The FTP server is connecting properly when I use FileZilla FTP tool manually (showing as it is connected through ftps over TLS (Implicit)
FtpClient fclient = new FtpClient(hostname, username, password);
fclient.EncryptionMode = FtpEncryptionMode.Implicit;
fclient.SslProtocols = SslProtocols.Tls12; //Also tried with TLS1 and TLS
fclient.Port = 990;
fclient.Connect();
Try this (taken from ConnectFTPSCertificate.cs example of FluentFTP). The important part is the callback OnValidateCertificate.
public static async Task ConnectFTPSCertificateAsync() {
var token = new CancellationToken();
using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
conn.EncryptionMode = FtpEncryptionMode.Explicit;
conn.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
await conn.ConnectAsync(token);
}
}
private static void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e) {
if (e.PolicyErrors == System.Net.Security.SslPolicyErrors.None) {
e.Accept = true;
}
else {
// add logic to test if certificate is valid here
// lookup the "Certificate" and "Chain" properties
e.Accept = false;
}
}
I experienced the same issue.
Pay attention that fluentFTP supports only external interfaces and not implicit
I also tried ftpWebRequest without success.
Try using winSCP.

Timeout in socket connection in UWP

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

C# server client fails on connect UWP

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

System.IO.IOException:Sharing violation on path - multiple clients

I have two applications. The server send files to my clients. The clients are implemented in Unity3d with C#. Each client has one thread to receive files from server. If I send the files over the network, I write the bytes to the file with this code:
private Thread clientThread;
private object writeLock = new object();
public void StartConnection()
{
// Start connection to server.
clientThread = new Thread(GetFiles);
}
public void GetFiles()
{
string fullPath;
// Receive bytes from server
fullPath = Path.Combine(clientDirPath, fileNameFromServer);
lock(writeLock)
{
using (BinaryWriter bWrite = new BinaryWriter(File.Open(fullPath, FileMode.Create)))
{
bWrite.Write(binaryFileContent);
bWrite.Flush();
}
}
Now, if I start multple clients and send files to receive them synchronously on the client-side, I get this error message: System.IO.IOException:Sharing violation on path. Whether I use the lock-statement it is not working. Do anyone know the way to get it working?
EDIT: I added more code.

Explorer OM is not supported in a 64bit process

I was trying to create send ports using C# .NET through following code :
using Microsoft.BizTalk.ExplorerOM;
private void CreateSendPort()
{
// connect to the local BizTalk Management database
BtsCatalogExplorer catalog = new BtsCatalogExplorer();
catalog.ConnectionString = "Server=.;Initial Catalog=BizTalkMgmtDb;Integrated Security=SSPI;";
try
{
// create a new static one-way SendPort
SendPort myStaticOnewaySendPort = catalog.AddNewSendPort(false, false);
myStaticOnewaySendPort.Name = "myStaticOnewaySendPort1";
myStaticOnewaySendPort.PrimaryTransport.TransportType = catalog.ProtocolTypes[0];
myStaticOnewaySendPort.PrimaryTransport.Address = "http://sample1";
myStaticOnewaySendPort.SendPipeline = catalog.Pipelines["Microsoft.BizTalk.DefaultPipelines.XMLTransmit"];
// create a new dynamic two-way sendPort
SendPort myDynamicTwowaySendPort = catalog.AddNewSendPort(true, true);
myDynamicTwowaySendPort.Name = "myDynamicTwowaySendPort1";
myDynamicTwowaySendPort.SendPipeline = catalog.Pipelines["Microsoft.BizTalk.DefaultPipelines.XMLTransmit"];
myDynamicTwowaySendPort.ReceivePipeline = catalog.Pipelines["Microsoft.BizTalk.DefaultPipelines.XMLReceive"];
// persist changes to BizTalk Management database
catalog.SaveChanges();
}
catch(Exception e)
{
catalog.DiscardChanges();
throw e;
}
}
Source
But I'm getting following issue
Explorer OM is not supported in a 64bit process.
when this line is executed :
BtsCatalogExplorer catalog = new BtsCatalogExplorer();
I'm well aware of the fact i.e. : "Warning
Microsoft.BizTalk.ExplorerOM.dll is only supported if used from 32 bit processes. If you are building a solution for a 64 bit system you should not use this library."
But in this case how can I create send ports on 64bit machine, Can anybody please help me with this?
Force it to run in a 32 bit process.
http://lostechies.com/gabrielschenker/2009/10/21/force-net-application-to-run-in-32bit-process-on-64bit-os/
As of BizTalk 2010, this restriction was lifted and ExplorerOM can be used in 64-bit and 32-bit processes.

Categories