0
votes

I’m setting up a StreamSocketListener in my UWP application to receive a request from a Windows Form client, Also, I want after the received special requested command (this command is String type) with TCP in my UWP application, It sending back some data in Byte[] or string to that client requested it.

My Code in UWP: I Initial that like this:

tcpListener = new StreamSocketListener();
tcpListener.Control.KeepAlive = false;
tcpListener.ConnectionReceived += TCPListener_ConnectionReceived;

and get data with:

private async void TCPListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                string request;
                using StreamReader streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead());
                using StreamWriter streamWriter = new StreamWriter(args.Socket.OutputStream.AsStreamForWrite());

                while (true)
                {
                    request = await streamReader.ReadLineAsync();
                    if (!string.IsNullOrEmpty(request))
                    {
                        switch (request)
                        {
                            case "Command1":
                                //Do somthing i want
                                

                                            await streamWriter.WriteLineAsync("Done.");
                                            await streamWriter.FlushAsync();
                                            //When Job done I want send some data in string to Client
                                break;
                            case string stringRequest when stringRequest.StartsWith("Text"):
                                //Do somthing i want
                            

                                            await streamWriter.WriteLineAsync("Done.");
                                            await streamWriter.FlushAsync();
                                            //When Job done I want send some data in string to Client

                                break;
                            default:
                                break;
                        }
                    }
                }



            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

I want get data back from UWP with some Command that send by TCPClient in my WinForm. In my WinForm Application I have:

using var tcpClient = new TcpClient ();
await tcpClient.ConnectAsync ("192.168.1.61", 1540);
using NetworkStream networkStream = tcpClient.GetStream ();

networkStream.ReadTimeout = 20000;

using StreamWriter streamWriter = new StreamWriter (networkStream);
using StreamReader streamReader = new StreamReader (networkStream, Encoding.UTF8);

streamWriter.AutoFlush = true;

await streamWriter.WriteLineAsync ("Command1");

byte[] bytes = new byte[tcpClient.SendBufferSize];

int recv = 0;
string received = string.Empty;
while (true) {
    received += streamReader.ReadLine ();
    if (received.EndsWith ("\n")) break;
}

Debug.WriteLine ($"Rec: {received}");

I can connect and sent command correctly but I can't received data back from server My UWP is Kiosk Application and I need get some data from that

1
You need two NetwokStreams. One for reading and one for writing.jdweng
Thanks but can you send me script to explain that?Feri
I found you have send response from UWP server to Form client Can't you read data from networkStream input flow?Nico Zhu - MSFT
Please try to delete if (received.EndsWith ("\n")) break; line, I suppose this line break the response.Nico Zhu - MSFT
@NicoZhu-MSFT Yes I want do that my client send command to UWP and UWP send back to itFeri

1 Answers

1
votes

I think this should be work:

First in StreamSocketListener ConnectionReceived method do something like this:

private async void StreamSocketListener_ConnectionReceived (StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) {

    try {

        string request;
        using StreamReader streamReader = new StreamReader (args.Socket.InputStream.AsStreamForRead ());

        while (true) {
            request = await streamReader.ReadLineAsync ();
            switch (request) {
                case "Command 1":
                    string screen = string.Empty;
                    try {
                        using DataWriter dataWriter = new DataWriter (args.Socket.OutputStream);

                        dataWriter.WriteString (scrennShotBase64); //or any you want like Byte
                        await dataWriter.StoreAsync ();
                        await dataWriter.FlushAsync ();
                        dataWriter.DetachStream ();
                    } catch (ArithmeticException ex) { Debug.WriteLine (ex); }
                    break;
                case "Command 2":
                    // do some...

                    break;
                default:
                    break;
            }
        }
    } catch (Exception ex) {
        Debug.WriteLine (ex.Message);
    }
}

And in your TCPClient do something like this:

try {
    using TcpClient tcpClient = new TcpClient ();
    tcpClient.ReceiveTimeout = 20000;
    tcpClient.NoDelay = true;
    tcpClient.ReceiveBufferSize = 20480000;
    await tcpClient.ConnectAsync ("192.168.1.1", 1338);
    using NetworkStream networkStream = tcpClient.GetStream ();
    networkStream.ReadTimeout = 20000;
    using StreamWriter streamWriter = new StreamWriter (networkStream);
    using StreamReader streamReader = new StreamReader (networkStream, Encoding.UTF8);
    streamWriter.AutoFlush = true;
    await streamWriter.WriteLineAsync ("Command 1");
    byte[] bytes = new byte[tcpClient.SendBufferSize];
    int recv = 0;
    string received = string.Empty;
    if (networkStream.CanRead) {
        StringBuilder CompleteMessage = new StringBuilder ();
        byte[] bytesR = new byte[102400];
        int numberOfBytesRead = 0;
        do {
            numberOfBytesRead = networkStream.Read (bytesR, 0, bytesR.Length);
            CompleteMessage.AppendFormat ("{0}", Encoding.ASCII.GetString (bytesR, 0, numberOfBytesRead));
        }
        while (networkStream.DataAvailable);
    } else {
        Debug.WriteLine ("You cannot read data from this stream.");
        tcpClient.Close ();
        networkStream.Close ();
        return;
    }
    networkStream.Close ();
} catch (Exception ex) {
    Debug.WriteLine (ex);
}

For more information, you can see this page on Microsoft!