I want to implement a chat application but I don’t want to use timeout because it checks every few seconds. Is there any other method to do this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use ajax to call to a php page that will hang until there is something new and then it sends that to the client, and after the ajax uses what it got, it can make another request to that page, that will hang again. This way you trade the requests to the server for server processing time. You can use usleep, and a while loop to keep the page alive, and don’t forget to set the execution time limit of page.
EDIT 1:
Well, I will suppose that you have a function to send data (I will call it
request), and asynchronously waiting for a response, and you linked a function to execute on response. Let’s call that functionlisten.And another function
sendthat sends the replies of user, or anything else. Bothsendandlistenwill request the same page, one with noPOSTorGETdata (listen), and one withPOSTdata containing the replies or other thing.The initial request will be done with
listen, or when you want to manually start the listener, and after a response. The other one is called anytime you send something.What is important is the php code.
If you are working in a linux environment you can use a lot of things like os signals, but in general we can use while, and usleep, so that we do not kill the server.
and now:
Now, you first call
listen, that will wait until it echoes an brake the loop, and when it does, you use the result, and then you calllistenagain. In case you want to send something, you usesend, that must brake the previous request and make a new one, that after it writes the data will start the listener. And so on, I hope you got the idea, tell me if you want to clarify it a bit.And do not forget to use
set_time_limit(0);at the start of the page.I might be a bit off, and need to review this code, but this is the main idea.