Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

c# - 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 
";
            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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...