4

I'm wondering if it's possible to send a response every second or so to a single http request. Like for example the client makes an http request, then the server sends a space character every second. This could be never ending or with a limit, for example a minute.

I think the word 'response' is misleading in this context, since I don't necessarily mean an http response. The whole http response could be composed of the space characters, which would mean a single http response to a single http request, except that it is a minute long.

I tried chunked encoding but I don't think it works, or at least my implementation's wrong.

luis
  • 51
  • 3

1 Answers1

5

You can use WebSockets to accomplish server-side pushing to the client. They allow you to open a connection to a server and receive responses from the server without issuing further requests from the client.

The websocketstest page shows a WebSocket connection working in your browser (if it supports WebSockets), with an update of the server time pushed to the client every second.

The socket.io JavaScript library is a popular way to implement a WebSocket on the client side, with fallbacks for older browsers and support for multiple sockets.

You'll also need to create a websocket server to listen for connections and serve responses. There are libraries for PHP, Java, Ruby, node.js, Python, and others. There's a tutorial here that talks you through the client and server -side setup.

Note that not all browsers support WebSockets by default, although the socket.io library attempts to workaround this [details].

Simon Hayter
  • 32,999
  • 7
  • 59
  • 119
Nick
  • 20,466
  • 4
  • 44
  • 81