What's the best way to retrieve messages from the server for a chat application

190 views Asked by At

I'm writing a chat application from scratch, and I'm trying to figure out the best way to retrieve messages from the server in real time. I've done a fair amount of research, and have come up with this: I could use web sockets, and I've seen it done before successfully. I could use long polling, but I'm wondering if that places greater stress on the server, or maybe is just not right for a chat application. I could poll the server every second, but that just seems like a waste of bandwidth. Suggestions? Thank you!

2

There are 2 answers

0
Kevin Michael On

The websocket protocol is ideal for something like a chat application for several reasons.

  • As you've already identified, continous polling of the server is quite a waste of resources.
  • Using traditional HTTP requires the use of bulky headers which waste valuable bandwidth. Websockets allow for lean messaging.
  • Most importantly for your application, unlike HTTP, websockets are bi-directional, meaning that your server can independently send messages to your chat client. With HTTP, all communication must be initiated by the client, and you are restricted to a request-response type of communication. With websockets, if your client receives a message from another user on your chat service, the server can immediately and independently relay that information to the intended recipient.

So to answer your question. You should definitely go with web sockets. Since you lack traditional headers, you will have to do a bit of work when it comes to formatting the messages sent over the connection, but the efficiency is well worth the minimal effort it takes to set up your messaging model.

0
Chris Terrell On

What? Do you need to and from a database on a dedicated server? I would recommend Ajax with JavaScript or jQuery but i like to do my own coding so JavaScript. If your showing data back and forth match i would probably use MySQL.

For example to query up the last known query if matches current then would not be updated. If doesn't match loop up from last to rent match would be DESC if in Order by type. Anyways... Hope this helps you decide on what you should use.

Although this is what is common on games, blogs, forums, chats with MySQL/SQL.