Home > Mobile >  TCP based chat application in WPF | C#
TCP based chat application in WPF | C#

Time:01-21

I am building a chat application based on TCP connection. They are basically two applications (one is server and another is client).

On the client application (after successfully connecting to the server), whenever I type a message in the textBox and send it (it happens successfully) but the issue is on the receiving side as when I run a thread to continuously check on the stream (NetworkStream object) the application i.e. client side freeze. An in the meanwhile I will be unable to send message,

In WPF side I created handle click event on the send button.(works fine)

And there is another listbox which is binded to the ObservableCollection which notify any change in the collection to the UI. But as I add the thread of conitnuously checking the NetworkStream for received messages, the UI hangs until the server is closed.

I want the application to not freeze while receiving as well as sending messages.

CodePudding user response:

EDIT: Okay so Long Polling is probably the best option here as per Andy. It's when you have the client continuously look for changes on the server side (e.g. whenever a new message is sent, the server will notify the client so that it can fetch and display it). This should prevent multiple requests from sending because there's no need to re-query the server as compared with repeated polling. Here's an example:

//On Client side       
var httpWebRequest = WebRequest.CreateHttp("server-url"); //get web request object       
httpWebRequest.Method = "GET"; //set method to GET       
httpWebRequest.BeginGetResponse(HandleResponseCallback, httpWebRequest); //send request   

//Callback function definition: 

void HandleResponseCallback(IAsyncResult result) {
  try {
    HttpWebResponse response = (HttpWebResponse) result.AsyncState;
    using(StreamReader reader = new StreamReader(response.GetResponseStream())) {
      string responseFromServer = reader.ReadToEnd(); //read responses      
      var message = JsonConvert.DeserializeObject < ChatMessage > (responseFromServer);
      if (message != null && message has changed) {
        MessageList collection adds / updates message here;
      }
    }
  } catch (Exception ex) {
    throw;
  }
}
  • Related