views:

128

answers:

2

Hi!

I wanted to create a web chat. It was suggested that i use Php Socket Servers. I've made one and they function well with a telnet client.
What i find myself bamboozled by is how to get that data to the client via ajax (no page refreshes).
All I can come up with is calling a php file with ajax, getting the data and updating the page. But that will not work the other way around.
Or am i missing something?

How would you implement a 1 on 1 web chat?

A: 

You've got the idea of client-initiated communication, which is fine for sending things from the client to the server.

As a consequence of the stateless nature of HTTP, there is no way to "push" data, unbidden, to the client.

The way you get around this is by always leaving a connection back to the server open. The request is pending, and when the server has something to say, it responds to the pending request. Whenever this happens, the client creates a new request to leave sitting until the next time server->client communication must happen.

Another way to implement near-real-time communication is through frequent polling. But I don't recommend this approach, really. Especially not for a chat program.

Borealid
A: 

One solution is long-polling. The client will open up an AJAX request to a script that will block and wait for data to come in. If no data comes in within a minute, it will return and the client will reopen the connection. If data comes in, then it will immediately return the data and the client will update its view.

For sending the data, just do a normal AJAX callback.

Yuliy
Do you have any example code for this?
Mark Tomlin
The client-side code remains the same. It's just that you'll actually receive data much later. The server would be something which has to manage a bunch of in-progress connections, and handle new data coming in, finds the appropriate connection(s) to send that data to, and sends that data.
Yuliy