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?
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.
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.