PHP/AJAX Long Polling: Returning New Content As It's Available
I am creating a PHP/AJAX chat client. The application makes an AJAX request to a PHP script which gets the contents of an XML file, and responds with the contents. The client then parses the XML and displays the chats. The XML file contains all the chats, but to save server resources, I would only like the PHP script to return new chats, instead of all the chats. Here is my XML file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<chat>
<message>
<hour>12</hour>
<minute>06</minute>
<half>AM</half>
<day>Saturday</day>
<month>March</month>
<date>19th</date>
<body>Hey Guys!</body>
</message>
<message>
<hour>12</hour>
<minute>08</minute>
<half>AM</half>
<day>Saturday</day>
<month>March</month>
<date>19th<开发者_如何转开发;/date>
<body>How are you?</body>
</message>
<message>
<hour>3</hour>
<minute>28</minute>
<half>PM</half>
<day>Saturday</day>
<month>March</month>
<date>19th</date>
<body>Good, thanks!</body>
</message>
</chat>
The <message>
tag defines each new chat, the tags <hour>
, <minute>
, <half>
, <day>
, <month>
, and <date>
define the time each chat was sent, and <body>
contains each chat.
This is the solution I have thought of:
- Adding a tag to the XML file that tells what number each chat is:
<number>12</number>
- In the AJAX request, having the client send the latest chat's number to the PHP script to check if it is the latest, and then having PHP continuously check the XML file for a
<number>
tag with a number greater than that, and then returning the chat when there is a number greater.
I don't know how well this would work, is there a better way to do this? Again, I just want the PHP script to return new chats as they come. Could someone please help me out or point me in the direction of something that might work? Thanks!
You're quite right with your idea but ... looking for new chats invloves opening your growing xml file for each request ... May become quite heavy for your server ! Why not using a database, it will be lighter, there may even be db that can use xml file as backend ...
Personally, I would log all chat messages in a database. Then, every x seconds run a query similar to the following:
SELECT *
FROM chat_messages
WHERE chat_id = 'your-chat-id'
AND time_sent > 'last-time-queried'
ORDER BY time_sent ASC
You could wrap this in a standalone script that returns the format in XML, and that you then use jQuery to hit. Then in your callback parameter loop over any returned XML nodes and insert them into your requesting document as new lines of chat text.
Maybe you are searching for a Comet solution? There a lot of threads discussing similar topics, as e.g.:
- Using comet with PHP?
- How to implement a chat room using Jquery/PHP?
Using comet with PHP?
精彩评论