如何通过 streamsocket 连续接收来自服务器的数据?

How can I receive data from server by streamsocket continuously?

我是一名WPF程序员,现在是UWP初学者

我现在需要编写一个新程序来连接远程机器。并且机器会时不时的给客户端发送数据。

我想让机器每次发送数据时,客户端都会立即得到它。

在WPF中我可以使用Asynchronous Client Socket,只要客户端有数据,ReceiveCallback就会get it at once as shown in this example

但是,在 UWP 中似乎没有异步客户端套接字。我使用 SteamSocket 成功连接远程机器,如下所示:

 Task.Run(async()=>{
                try
                {
                    StreamSocket SS = new StreamSocket();
                    await SS.ConnectAsync(new Windows.Networking.HostName("192.168.200.111"), "23");

                    DataWriter writer = new DataWriter(SS.OutputStream);
                    string content = "ST";
                    byte[] data = Encoding.UTF8.GetBytes(content);
                    writer.WriteBytes(data); 
                    await writer.StoreAsync();
                    writer.DetachStream();
                    writer.Dispose();

                    DataReader reader = new DataReader(SS.InputStream);
                    reader.InputStreamOptions = InputStreamOptions.Partial;
                    await reader.LoadAsync(1024);
                    string response = reader.ReadString(reader.UnconsumedBufferLength);
                    Debug.WriteLine(response);                       
                }
                catch(Exception ex)
                {
                    throw ex;
                }
            });

然而,这些代码只能在您使用DataReader时读取数据,但不会在收到数据时立即显示。

通过使用环回可能会解决它,我不希望代码因环回而变得如此丑陋。

我用谷歌搜索但没有发现任何有用的信息。

我问过微软工程师,他告诉我用SocketActivityTrigger,我不想用它,不仅难用,而且是后台工作者.即使我退出UWP程序,它仍然会连接到远程机器并不断接收数据。

请问如何解决?


致@Nico Zhu:

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            Task.Run(async()=>{
                try
                {                    
                    StreamSocketListener SSL = new StreamSocketListener();
                    SSL.ConnectionReceived += SSL_ConnectionReceived;
                    await SSL.BindEndpointAsync(new Windows.Networking.HostName("192.168.200.111"), "23");

                }
                catch(Exception ex)
                {
                    throw ex;
                }
            });
        }

        private void SSL_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("123");
        }

我用的是StreamSocketListener,但是我运行这个程序后,报 '

{System.Runtime.InteropServices.COMException (0x80072741): The requested address is not valid in its context

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at App2.MainPage.<<Button_Click>b__2_0>d.MoveNext()}

' 这有什么问题吗?

感谢@Nico Zhu 对我的帮助。最后,我找到了一个奇怪的方法:在UWP

中使用WPF的socket 但是奇怪的是WPF的socket没有UWP中的Asynchronous Client Socket,所以只能这样了:

 await Task.Factory.StartNew(async () =>
            {
                IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.200.111"), 23);
                Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                S.Connect(ip);
                S.Send(Encoding.UTF8.GetBytes("SS" + Environment.NewLine));
                while (true)
                {
                    byte[] buffer = new byte[1024];
                    if (S.Available != 0)
                    {
                        S.Receive(buffer);
                        Debug.WriteLine(Encoding.UTF8.GetString(buffer));
                        Debug.WriteLine("");
                        await Task.Delay(100);
                    }
                }
            });