Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Online Chat using Pooling

I need help in doing an online chat. I already created a simple online chat where one user can communicate to another user and their conversation is saved as a json file. The json file is what I am reloading after every 2secs using setInterval(). The message the users are sending are appended on the json file by posting it using ajax and through php function fopen and fwrite(append).

My problem is that the sending/posting process on my ajax is too slow. It takes time before the user see his/her message was send on the chat screen(div). I tried appending the message on the screen to look as if it is already sent but the problem is when the setInterval reloads the chat screen and the new appended message is not yet saved on the json file, the newly sent message will not be included on that reload.

Questions:

  1. How can I append the new message faster?
  2. How can I queue the multiple post on my ajax when the user is typing and sending message too fast?
  3. PS: Is their a better way of creating a online chat? I've read that I am using pooling on my chat and the better way is by using socket but I have no idea on using it. Do you have a better way or better logic?
like image 600
jroi_web Avatar asked Jun 08 '26 05:06

jroi_web


1 Answers

Few Points to consider:

-> Search about Long Poll (COMET)

-> Why do setInterval refreshes the screen, it should just append the new messages from the server

-> If you are using HTML5 based browsers, check Websockets and Server Side Events.

-> Use DB operations on server side, instead of File operations. It will also improve maintainability, consider a case in which 1000 different users are chatting with each other, it will be difficult to maintain those files.

-> Server should send the delta messages which are new, it should not just send the whole conversation again to client to parse and reload.

like image 155
Nitin Midha Avatar answered Jun 10 '26 18:06

Nitin Midha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!