简体   繁体   中英

Send information from a server to a client

I'm looking for a way to send information from a server to a client, for example a song or an image.

Explanation : I want to send a data from my server to the clients who downloaded the HTML5 application.

But I dont know how. I know I can send a php request from the client to the server and answer afterwards, but how could I send something from the server without the client ask it.

Thanks.

You may want to try either Server-Sent Events or WebSockets:

These technologies allow a client web application to remain open to communication from the server at any time. Server-Sent Events are exclusively server-to-client, whilst WebSockets can be used for bi-directional communication.

Adding to jokeyrhyme's answer...

You want to asynchronously send data from the server to the client. This means the client doesn't know when to expect the data. In practical terms, on today's Web, you have the following options:

  • Some form of polling, long polling, Comet, etc.
  • WebSocket

The first option is better understood since those techniques have been around for a long time.

WebSocket is newer but is the better solution as it alleviates the problems that plague HTTP-based techniques with polling, long polling, etc. For a small application, or one that polls infrequently, you can get away with polling. But when you want to scale, those solutions run into problems.

I would not bother with SSE (Server-Sent Events) as that is pretty much a subset of WebSocket. Anyone considering SSE usually ends up just using WebSocket since it's about the same amount of work and it gives you more (eg two-way interaction).

However WebSocket doesn't replace HTTP; an application can use both at the same time. Use the right tool for the right job.

In your case, have a client with a WebSocket connection. Then your backend application can notify the client at any time (asynchronously) that there is something to do (eg a new song or image is available, as you said in your original post).

I would not bother sending the song or image down the WebSocket connection, although you could. Instead, the client can fetch the song or image using traditional HTTP techniques, which are well understood and good at handling static content. For example, you can take advantage of caching if multiple people are downloading the same (song or image) file.

So, send the id or URL of the song/image to be downloaded via the WebSocket to the client. Then fetch the song/image via HTTP.

That's an example of using both HTTP and WebSocket for their strengths. WebSocket for the efficient asynchronous interaction with virtually no bandwidth consumption, and HTTP for efficient fetching of static resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM