问题
How to implement a real fast web chat with PHP?
Has anybody ever wonder why Facebook chat is just so really really fast? even in IE without WebSocket.
Isn't the only way is to setInterval in JS to check for new messages? But I feel it (Facebook chat box) like having instant reaction.
How to implement such great thing with PHP?
回答1:
The instantaneous chat you're describing is generally acheived by a something called "Long Polling" or, if we're talking about AJAX, "Comet" (Wikipedia talks about it). Polling tends to strain Apache servers, but there are some specialized servers to deal with it like APE. I'm not sure but I think you can do the same with NodeJS and NGINX handles the stress pretty well.
Here's an article here about how to implement a long polling chat with PHP jQuery and AJAX.
Best of luck, and I hope it helped!
回答2:
I agree with @joseph-szymborski although it would make sense to start looking at WebSocket solutions which fallback to WebSockets via Flash and/or long-polling.
Here are some relevant SO questions:
- How to implement facebook like notification on cakephp? - PHP/jQuery
- ajax Push system - PHP/Ajax
- Apache with Comet Support - the question itself is very good.
- PHP Jquery: chat system, what is the Ideal framework for this? - relevant to your question.
If you want to work with PHP or are on shared hosting then I'd recommend looking at a hosted realtime web solution.
回答3:
You might want to consider Node.js to serve the clients in 'real time' since Long polling with PHP/AJAX may cause strain on your server. But the implementation itself is an uphill task. Just saying. Long polling with PHP/AJAX may cause strain on your server.
My typical theoretical implementation of the same:
- Create a Node.js server to query a database.
- Send variables and/or session data from php to Node js using cURL.
- Parse the url in your Node.js server and use the variables to check for changes in database.
- Emit new data if changes occur and send to client.
来源:https://stackoverflow.com/questions/8176937/how-to-implement-a-real-fast-web-chat-with-php