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
networkStream
input flow? – Nico Zhu - MSFTif (received.EndsWith ("\n")) break;
line, I suppose this line break the response. – Nico Zhu - MSFT