how to receive msg from client app through TCPserver in WPF

246 Views Asked by At
namespace Server_App
{
    
    public partial class MainWindow : Window
    {
        public TcpListener server;
        public Socket socket;
        public NetworkStream ns;
    
    public MainWindow()
        {
            InitializeComponent();

            server = new TcpListener(8888);
            server.Start();

            

}

 private void btn_Click(object sender, RoutedEventArgs e)
        {
         
            socket = server.AcceptSocket();
            ns = new NetworkStream(socket);
            StreamReader sr = new StreamReader(ns);
            tb.Text = sr.ReadLine();
            ns.Flush();
            ns.Close();
            socket.Close();
      
        }
}}

whenever I send msg from my android mobile it receive on my serverapp when I button click. But I want to to do that it contentiously receiving my msgs without clicking button every time. I try while(true) statement but I don't know it's not working. Remember it's WPF serverapp Can anyone help me?

1

There are 1 best solutions below

0
On

Do not do it in the constructor of the MainWindow, but in an event associated with the creation process of the mainwindow so you can add async to it.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private async void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var server = new TcpListener(IPAddress.Parse("0.0.0.0"), 8888);
        server.Start();
        while (true)
        {
            var client = await server.AcceptTcpClientAsync().ConfigureAwait(false);
            
            
        }
    }
}


<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Grid>
    
</Grid>

Go through it with a debugger. normally accepttcpclient is a blocking call. And also here you are awaiting it to become available. But because it uses async await, your GUI thread becomes available. You can move and resize the window because of this mechanism. Try this without async and await, and chances are your window will not even show because the loaded event never finishes. But I did not test this. Anyway without async await or using a different thread, your GUI thread would block

Async await is a more modern approach compared to using threads.