How to send AJAX messages to websocket users - php

I've implemented realtime chat in Websockets and it works just like a charm. I did it side by side with AJAX polling (which existed before), as I didn't want to remove AJAX polling support for older browsers, so although Websockets will be preferred, I am keeping polling as an option.
The way I have the websocket code set up is to:
Use Websockets to send the messages to the appropriate connections
Log the message in the database
The way the AJAX send works is:
Log the message in the database
The way the AJAX poll works is:
Check when user last retrieved messages for a room, and retrieve all messages since then
I have more of a conceptual question about how to get the two to work with each other. Assume I have User A and User B. If User A and User B are either both using AJAX polling or both using websockets, there are no issues whatsoever. It works as you would expect. But take the case when User A is using websockets and User B is using AJAX polling.
A → B
User A sends message via websocket
Chat message gets sent to all relevant connections. In this case, it just echoes back to User A, since User B is not using websockets.
Chat messages gets logged into database
User B requests new messages, and User A's message is sent back to him
B → A
User B sends message via AJAX
Message gets saved in database
?
This is what I'm hung up on. Websocket -> AJAX user messages work because the message ends up in the database where it can be polled by an AJAX user. But websocket users don't poll the database at all, so messages from AJAX users have no way of getting into the pipeline. Currently, websocket users don't see any messages from AJAX users. They only see them if they do a full page reload, at which point all messages get retrieved directly from the database.
What would be the appropriate method to allow some way for messages from AJAX users to get sent out via websocket to relevant websocket users? Basically, how can I communicate in the other direction?
The only thing I've been able to find on this subject is this slideshow - however, I'm not using longpolling, and I'm not entirely sure what it means by "providing that" to the websocket app. Does that mean put the onus on the websocket server to check for new AJAX messages? Is there no way to "push" from the AJAX script to the websocket server?

Thanks to ADyson for some ideas on how to approach this. This is what I ended up doing:
I have my JS clients ping the server every few seconds. For AJAX users, it's more frequent because they need to poll for messages. For Websocket users, they don't need to poll for websocket messages, so they poll every 15s to "check in". This has the benefit of functioning as an infinite loop essentially for each client, which is exactly what the idea requires.
What I did was essentially add a column to the messages table that keeps track of the message source: 0 for AJAX and 1 for WebSocket. Then, I modified the function that retrieves messages to take in an $ajaxOnly parameter. When I call this on an AJAX poll, it's false. For websocket polls, I call it with true instead. The result is for all rooms a user is in, it polls the DB and checks if there are any new AJAX messages. If there are, it sends them back to the client.
There are 2 caveats:
Messages will appear out of order. Websocket messages are relayed in realtime, so an AJAX message sent before a Websocket message could appear earlier to another AJAX user but later to other Websocket users.
This is not realtime. It's as slow as your poll interval, which in my case is 15 seconds for websockets since polls are very DB-intensive. AJAX polls are more frequent because they need to be to get any messages at all.
This isn't a perfect solution, but it does meet the goal of allowing AJAX messages to show up for websocket users in near-realtime. For me, I wanted to fully support AJAX and WebSocket, but AJAX is more for compatability and ideally most people will use WebSockets, so the fact that this isn't a great solution doesn't concern me too much, since it does get the job done.
If you were hoping for a realtime solution (like I was), you're going to be disappointed by this, but this is at least a workable solution so I've adopted it until something better comes up. You can make it near-realtime by increasing the frequency with which clients ping your server.

Simple solution:
When you save the message into the Datebase, push it to the Websocket Clients as well.

Related

Chat that works without AJAX

I've come across a live chat on a website and i was wondering how it would work?
The reason being is i thought it would be the normal AJAX based chat where it updates the messages by sending an AJAX request x amount of seconds or by using PHP sleep() to keep the connection open until new messages were sent.
However upon inspecting it using firebug, i couldn't see any AJAX requests being sent, when i was sending a message and when new messages were being retrieved. How does this work?
It's most likely using the Websockets protocol: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API. However, it's also possible it's using Flash.

Multiple Ajax request and it's downside

I am building a Mobile Application (Phone, Jquery Mobile) for Android.
It requires a user sending a message to the server side script using an Ajax request. I implemented a system such that messages sent are not sent immediately, instead they are stored in a SQLite database (this is so because, I want the user to think the message is sent even if the network is bad) and an iteration that runs every 15 seconds in the background picks it up and send it. So therefore, if 5 messages are in the SQLite database, they will be sent every 15 seconds apart.
The above system works fine when I tested it with my Android phone connected to my WAMP via Wi-Fi.
The problem I now foresee is that when I deploy on a production Server, the Ajax response from the server won't be that fast.
Is there a way to avoid a potential problem?
Note: The response from server is via json and it is essential because it will be used to delete the message from the phone SQlite Database.
Here is how I read your question:
A user interacts with the app and this generates actions that need to be updated on your backend. (for example, "like a post", "upvote a coment" etc.)
You have decided that the action does not need to complete synchronously and that the user does not need to wait around for the action to be completed/acknowledged; The user can continue on with new actions. At some point, the user will see that the actions have been processed but immediate updates aren't important.
Your polling loop in the app is responsible for eventually sending the actions to the backend to be completed. The backend acknowledges the action has been completed by sending a response back to the app to delete the pending action.
My answer based on above:
Since it is the app waiting on your custom protocol to complete and not the user waiting on a synchronous action to complete, you have a lot of flexibility in the server's response times.
More important is that your little protocol makes sure to eventually process the action on the backend and notify the client app. You are dealing with the concept of things becoming "eventually consistent" and thus you need to design your little protocol around that:
http://en.wikipedia.org/wiki/Eventual_consistency

auto update bids - PHP/Ajax

I want to create a bidding system where user can see the current price of items. And if any other user on any other location place a bid before me it should auto update bid in my browser.
I have read about autoupdate JS+Ajax functions but even if I place a 5 second timer to auto update the content on user's browser will it not put some extra load on server by making an ajax call every 5 second? Its a bidding system so user will have bids updating within 1-2 seconds so if i put an auto update ajax call for every 1-2 seconds it will put a lot of burden on server.
So I am wondering is there any better way to handle this type of stuff? how do twitter/facebook do update user's feeds?
AJAX or not, bidding systems always have high requests because people keeps refreshing the page to check for the latest bid information.
You can take a look and attempt long polling. Long polling a method where you "push" data from the server to the browser in response to the browser's HTTP request. It is a normal HTTP connection. This may reduce the number of requests sent from users to server, however you will still have many open and active connections between your users and your server.
You will want to look at long polling. In essence, this is how it works
On the server you need some sort of event mechanism (no probem with PHP)
Client (Browser) starts an AJAX request referencing a bidding item
Server checks for changes on the bid, if there is one, returns the request
If not, he waits for some time (minute range), waiting on an event concerning this bid
If such an event occurs, server returns the request with the info, if not he returns the request with "no bid" info
You might be able to get away with a streaming model...
Each JS client connects to the server once and keeps the conneciton open. As new events arrive at the server, they are broadcast to all the open connections in real time.
This is similar to the mechanism twitter uses to broadcast tweets.

How to speed up a jquery/php/ajax chatroom?

I've created a small jquery and php chatroom with some .get and .post functions and php docs that read and write data to a sql server. It works fine, but the small problem is when someone posts something, it takes about half a second for it to appear (because of the lag).
I fear there's something wrong with my coding.
im using
setinterval (listen, 300)
as my continuous jquery function for reading new db entries, listen is a function with a .get inside. How does stackoverflow or facebook do it so that the user types something in and immediately it pops out?
Maybe try displaying the inputted chat message immediately to the user who posted it, prior to posting it to the database.
Like this:
User enters message, submits
Update users chat window so they see it immediately
POST message to database
GET from db and update all chat windows
This can be implemented using various techniques, which have many names: Long-polling, Server Sent Events, Comet, WebSockets, and others.
Basic idea is this:
Alice opens facebook. Her browser makes a request for updates ($.get, for example), but the server does not respond if there are no new updates and the request remains in 'waiting' state.
Bob opens facebook. He decides to comment on Alice's wall. His browser posts his comment to the server ($.post).
The server accepts this post, handles it properly (saves onto Alice's wall, etc)
But ALSO server checks if there is a waiting update request from Alice. If there is, server renders info about this update into response stream and closes the connection.
Alice's browser finally gets a response to this long hanging request and happily draws a red "1" in the notification area. It also immediately opens another update request (to not miss any).
Alice sees comment from Bob, which was delivered instantly.
The technique described is called "long polling" and it was first introduced by Google in Gmail.
You can use HTML5 sockets, however these are very much in their infancy and not widely supported (i.e. by IE).
Lots of systems use Flash as a middle-man as that can hold a connection open.
With either of these you can use your PHP code that stores the comment to the database to also push this out to every "listener". This will be the quickest way possible. If your system is super clever it'll incorporate all three - HTML5 sockets where it can, Flash where it can't, and your regular polling were there's no Flash either.
http://pusher.com/ might be a good starting point for further learning.
Most sites that have fast chat use a technique called comet. You can read more about it here: http://ajaxian.com/archives/comet-a-new-approach-to-ajax-applications
It essentially is a piece of modified server software that waits to return a response to the user until either a message is sent or it is about to timeout.

How can I build a PHP/MySQL live chat?

I want to learn how to make one of these systems from scratch and I'm find a lot of junk links on Google. I really just want a simple tutorial for the most basic PHP and MySQL chat so I can understand the concept before I start messing with jQuery/AJAX.
PHP/MySQL chat 101:
1) user opens a browser
2) user enters address in brower
3) browser sends HTTP request
4) server recieves HTTP request
5) server tells PHP interpreter to run PHP script
6) PHP script connects to MySQL database
7) PHP script retrieves list of messages
8) PHP generates HTTP response made of HTML code with messages and form
9) Server sends HTTP response to browser
10) Browser draws HTML from HTTP response
11) User types new message and submits the form
12) Browser send HTTP POST request
13) ...
A very simple starting point
Have a database table for a Message
id | user | timestamp | message
And have a PHP page that sends an AJAX request to read any new messages.
This will involve checking the database to see if there are any messages since the time the request was received. If no messages, then loop, wait and try again in 100ms (or whatever you think is acceptable lag).
When the Ajax request returns a message (a JSON response would be best), output the user, time and message to the page using JQuery.
The live part of your chat is the tricky part, if you are just beginning i would skip that.
Start by building a simple guestbook, and then add more features.
There are many tutorials available on how to build a guestbook, and even some free scripts where you can learn from.
After you got your guestbook working, you could add features like auto-loading new messages to make it appear as live, using AJAX polling. What you basically do make an AJAX call to the server at a regular interval to get all the messages and display it on your page.
Found very interesting tutorial here
http://tutorialzine.com/2010/10/ajax-web-chat-php-mysql/
If you must use php and mySQL for chat, atleast have a seperate table for unread messages. If you poll you will most likely need to check the database for new messages every 100ms or so. If your total message table is 1000 rows checking every 100ms will kill your server (especially if many users are connected). I would structure my mySQL database with a table for only unread messages and move them to a bigger table for old messages once read. That way your not checking a big table all the time.
Even better is to use a cache database for unread messages like redis (facebook used memcacheD).
Even even better is to just not use php all together and use an event driven language with callbacks like node.js

Categories