开发者

Javascript to socket server conneciton

I wanted to create a web chat. It was suggested that i use Php Socket Servers. I've made one and they function w开发者_JAVA技巧ell 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜