服务工作者是否不断请求,来自服务器的响应? [英] does service worker request, response from server continuously?

查看:56
本文介绍了服务工作者是否不断请求,来自服务器的响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用服务器发送事件来显示通知.我已经创建了一个服务工作者,并且一旦我运行了项目,我就使用 EventSource 与服务器连接(在我的例子中我使用了一个 servlet.).一切正常.

I'm using server send event to display a notification.I have created a service worker and i used EventSource to connect with the server (in my case i used a servlet. ) once i run the project. everything is working fine.

但是事件里面的内容是countiously执行的.我想知道为什么?我的另一个问题是

but the contents inside the event execute countiously. I want to know why? my other question is

一旦我关闭标签.它停止发送通知.Service Worker 正在运行,服务器也在运行.但为什么它会停止?

once i close the tab. it stops sending notification. service worker is nunning and server also running. but why it stops?

这是我的 Service Worker 代码.

this is my service worker code.

var eventSource = new EventSource("HelloServ");
//MyDiv1 is a custom event
eventSource.addEventListener("MyDiv1",function(event){
    console.log("data from down" , event.data);

    var title = event.data;
    //below notification is displaying continuously. why ?
var notification = new Notification(title, {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: event.data,
});
notification.onclick = function () {
window.open("http://ageofthecustomer.com/wp-content/uploads/2014/03/success.jpg");      
        };
    console.log("down");
}); 

这是我的servlet代码;

this is my servlet code;

response.setContentType("text/event-stream");   
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        String upVote = "my up vote";
            writer.write("id:1\n");
            writer.write("event:myid\n");
            writer.write("data: "+ upVote +"\n");
            writer.write("data: "+"new data 2\n\n");
            System.out.println("servlet "+ i);
            writer.flush();
            i++;
writer.close();

推荐答案

Service Worker 的生命周期是有限的,您不应该使用 Web 套接字或服务器发送事件之类的东西.推送通知的实现方式不同.

Service workers have a limited lifetime, you shouldn't use things like web sockets or server sent events. Push notifications are implemented in a different way.

在您的页面中,您需要为用户订阅推送通知.订阅是一个端点 URL(和一组密钥,如果您计划使用有效负载).用户订阅后,您需要将订阅信息发送到您的服务器.

In your page, you need to subscribe the user for push notifications. The subscription is an endpoint URL (and a set of keys, if you plan to use payloads). Once the user is subscribed, you need to send the subscription information to your server.

服务器将通过对端点 URL 的 POST 请求向用户发送推送通知.

The server will send a push notification to the user via a POST request to the endpoint URL.

当推送通知到达时,Service Worker 将被唤醒,其推送"事件处理程序将被执行.

The service worker will be awakened when a push notification arrives, its 'push' event handler is going to be executed.

一个简单的例子(对于更复杂的例子,请查看ServiceWorker Cookbook).

A simple example (for more complex ones, take a look at the ServiceWorker Cookbook).

页面

// Register a Service Worker.
navigator.serviceWorker.register('service-worker.js')
.then(function(registration) {
  // Use the PushManager to get the user's subscription to the push service.
  return registration.pushManager.getSubscription()
  .then(function(subscription) {
    // If a subscription was found, return it.
    if (subscription) {
      return subscription;
    }

    // Otherwise, subscribe the user (userVisibleOnly allows to
    // specify that you don't plan to send notifications that
    // don't have a visible effect for the user).
    return registration.pushManager.subscribe({
      userVisibleOnly: true
    });
  });
}).then(function(subscription) {
  // subscription.endpoint is the endpoint URL that you want to
  // send to the server (e.g. via the Fetch API or via
  // XMLHTTPRequest).
  console.log(subscription.endpoint);

  // Here's an example with the Fetch API:
  fetch('./register', {
    method: 'post',
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify({
      endpoint: subscription.endpoint,
    }),
  });
});

服务工作者

// Register event listener for the 'push' event.
self.addEventListener('push', function(event) {
  // Keep the service worker alive until the notification is created.
  event.waitUntil(
    self.registration.showNotification('Title', {
      body: 'Body',
    })
  );
});

服务器

在服务器中,只需向端点 URL 发送 POST 请求.例如,使用 curl:

In the server, simply send a POST request to the endpoint URL. For example, with curl:

curl -X POST [endpointURL]

或者,如果你使用 Node.js,你可以使用 web-push 库(https://github.com/marco-c/web-push):

Or, if you're using Node.js, you can use the web-push library (https://github.com/marco-c/web-push):

var webPush = require('web-push');
webPush.sendNotification(req.query.endpoint, req.query.ttl);

在 Java 中,你可以使用这个类 (https://github.com/marco-c/java-web-push) 隐藏了实现细节以及当前版本的 Firefox 和 Chrome 中协议之间的差异(差异注定会消失,因为 Chrome 即将使用 Web Push 协议).这是一个手动"示例,其中包含实现 Web Push 协议的推送服务(目前仅适用于 Firefox):

In Java, you could use this class (https://github.com/marco-c/java-web-push) that hides the details of the implementation and the differences between the protocols in the current versions of Firefox and Chrome (differences destined to disappear since Chrome is going to use the Web Push protocol soon). Here's a "manual" example with a push service that implements the Web Push protocol (currently only works with Firefox):

URL url = new URL(endpointURL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write("");
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
  System.out.println(line);
}
writer.close();
reader.close();

这篇关于服务工作者是否不断请求,来自服务器的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆