苹果平台开发的应用程序,不支持后台运行程序,所以苹果有一个推送服务在软件的一些信息推送给用户。
JAVA中,有一个开源软件,JavaPNS实现了Java平台中连接苹果服务器与推送消息的服务。但是在使用的过程中,有两点需要使用者注意一下,希望后续使用的同志们能避免我走过的覆辙。
1、一是向苹果的服务推送消息时,如果遇到无效的deviceToken,苹果会断开网络连接,而JavaPNS不会进行重连。苹果原文:
If you send a notification and APNs finds the notification malformed or otherwise unintelligible, it returns an error-response packet prior to disconnecting. (If there is no error, APNs doesn’t return anything.) Figure 5-3 depicts the format of the error-response packet.
2、JavaPNS是一条条发送通知的,但是对于大规模发送的生产环境,显然是不可以的,建议使用批量发送。苹果原文:
The binary interface employs a plain TCP socket for binary content that is streaming in nature. For optimum performance, you should batch multiple notifications in a single transmission over the interface, either explicitly or using a TCP/IP Nagle algorithm.
对于此,我对JavaAPNS的代码进行了改动,使其支持批量发送和苹果断开重连,但是有一个问题需要大家注意一下,在正常发送的情况下,苹果是不会向Socket中写任何数据的,需要等待其读超时,this.socket.getInputStream().read(),确订推送结果的正常。通过持续的向Socket中写数据,实现批量发送,调用flush方法时,完成一次批量发送。在PushNotificationManager增加如下方法:
Java代码
- public List<ResponsePacket> sendNotification(List<PushedNotification> pnl) {
- logger.info(psn + "RR批量推送时消息体的大小为:" + pnl.size());
- List<ResponsePacket> failList = new ArrayList<ResponsePacket>();
- if (pnl.size() == 0) {
- return failList;
- }
- Set<Integer> sendSet = new HashSet<Integer>();
- int counter = 0;
- while (counter < pnl.size()) {
- try {
- this.socket.setSoTimeout(3000);
- this.socket.setSendBufferSize(25600);
- this.socket.setReceiveBufferSize(600);
- for (; counter < pnl.size(); counter++) {
- PushedNotification push = pnl.get(counter);
- if (sendSet.contains(push.getIdentifier())) {
- logger.warn("信息[" + push.getIdentifier() + "]已经被推送");
- continue;
- }
- byte[] bytes = getMessage(push.getDevice().getToken(), push.getPayload(), push.getIdentifier(), push);
- this.socket.getOutputStream().write(bytes);
- // 考虑到重发的问题
- // sendSet.add(push.getIdentifier());
- }
- this.socket.getOutputStream().flush();
- // 等待回馈数据,比单个发送时延时长一点,否则将无法获取到回馈数据
- this.socket.setSoTimeout(1000);
-
- StringBuffer allResult = new StringBuffer();
- ResponsePacket rp = new ResponsePacket();
- int readCounter = 0;
- // 处理读回写数据的异常
- try {
- logger.info(psn + "检查流数据是否可用:" + this.socket.getInputStream().available());
- byte[] sid = new byte[4];// 发送标记
- while (true) {
- int value = this.socket.getInputStream().read();
- if (value < 0) {
- break;
- }
- readCounter++;
- if (readCounter == 1) {
- rp.setCommand(value);
- }
- if (readCounter == 2) {
- rp.setStatus(value);
- }
- if (readCounter >= 3 && readCounter <= 6) {
- sid[readCounter - 3] = (byte) value;
- if (readCounter == 6) {
- rp.setIdentifier(ByteBuffer.wrap(sid).getInt());
- if (failList.contains(rp)) {
- logger.error("错误返馈数据中已经包含当前数据," + rp.getIdentifier());
- }
- failList.add(rp);
- }
- }
- allResult.append(value + "_");
- }
- this.socket.getInputStream().close();
- } catch (SocketTimeoutException ste) {
- logger.debug(psn + "消息推送成功,无任何返回!", ste);
- } catch (IOException e) {
- logger.debug(psn + "消息推送成功,关闭连接流时出错!", e);
- }
- logger.info("苹果返回的数据为:" + allResult.toString());
- if (readCounter >= 6) {
- // 找到出错的地方
- for (int i = 0; i < pnl.size(); i++) {
- PushedNotification push = pnl.get(i);
- if (push.getIdentifier() == rp.getIdentifier()) {
- counter = i + 1;
- break;
- // 从出错的地方再次发送,
- }
- }
- try {
- this.createNewSocket();
- } catch (Exception e) {
- logger.warn("连接时出错,", e);
- }
- }
- } catch (SSLHandshakeException she) {
- // 握手出错,标记不加
- logger.warn("SHE消息推送时出错,", she);
- try {
- this.createNewSocket();
- } catch (Exception e) {
- logger.warn("连接时出错,", e);
- }
- } catch (SocketException se) {
- logger.warn("SE消息推送时出错", se);
- counter++;
- try {
- this.createNewSocket();
- } catch (Exception e) {
- logger.warn("连接时出错,", e);
- }
- } catch (IOException e) {
- logger.warn("IE消息推送时出错", e);
- counter++;
- } catch (Exception e) {
- logger.warn("E消息推送时出错", e);
- counter++;
- }
-
- if (counter >= pnl.size()) {
- break;
- }
- }
- return failList;
- }
评论
在javapns2.2 中,重发确实存在bug。但是我发现。在注释重发后,notifications的返回结果会变得非常不准确(虽然不注释也不准确),所以根据系统的需求,如果需要比较准确的返回结果,还是不注销重发比较好,如果系统偏重与推送功能,对推送结果没有很高的要求,注释掉重发代码可以修复重复推送的bug。期待在以后的javapns版本中修复重复推送的bug。
在正常发送的情况下,苹果是不会向Socket中写任何数据的,需要等待其读超时。想问一下楼主,这个苹果读取超时是在哪看到的,能否给个链接?
lz,,,,你的
持续写入数据,遇到无效的deviceToken苹果会断开连接,并返回相应的消息编号,这时需要重新连接,再次发送数据
博文体现在哪里?是从这里开始吗:
if (readCounter >= 6) {
// 找到出错的地方
如果是,lz可以去看看javapns2.2版本的
PushNotificationManager.stopConnection()这个方法。这里面实现了重发。望回复。
请问,你的这个方法的输入参数: List<PushedNotification> pnl 怎么创建?
lsqwind 写道
rock 写道
PushQueue支持重连,
源码:
Java代码
- private void sendNotification(PushedNotification notification, boolean closeAfter) throws CommunicationException {
- try {
- Device device = notification.getDevice();
- Payload payload = notification.getPayload();
- try {
- payload.verifyPayloadIsNotEmpty();
- } catch (IllegalArgumentException e) {
- throw new PayloadIsEmptyException();
- } catch (Exception e) {
- }
-
- if (notification.getIdentifier() <= 0) notification.setIdentifier(newMessageIdentifier());
- if (!pushedNotifications.containsKey(notification.getIdentifier())) pushedNotifications.put(notification.getIdentifier(), notification);
- int identifier = notification.getIdentifier();
-
- String token = device.getToken();
- // even though the BasicDevice constructor validates the token, we revalidate it in case we were passed another implementation of Device
- BasicDevice.validateTokenFormat(token);
- // PushedNotification pushedNotification = new PushedNotification(device, payload);
- byte[] bytes = getMessage(token, payload, identifier, notification);
- // pushedNotifications.put(pushedNotification.getIdentifier(), pushedNotification);
-
- /* Special simulation mode to skip actual streaming of message */
- boolean simulationMode = payload.getExpiry() == 919191;
-
- boolean success = false;
-
- BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
- int socketTimeout = getSslSocketTimeout();
- if (socketTimeout > 0) this.socket.setSoTimeout(socketTimeout);
- notification.setTransmissionAttempts(0);
- // Keep trying until we have a success
- while (!success) {
- try {
- logger.debug("Attempting to send notification: " + payload.toString() + "");
- logger.debug(" to device: " + token + "");
- notification.addTransmissionAttempt();
- boolean streamConfirmed = false;
- try {
- if (!simulationMode) {
- this.socket.getOutputStream().write(bytes);
- streamConfirmed = true;
- } else {
- logger.debug("* Simulation only: would have streamed " + bytes.length + "-bytes message now..");
- }
- } catch (Exception e) {
- if (e != null) {
- if (e.toString().contains("certificate_unknown")) {
- throw new InvalidCertificateChainException(e.getMessage());
- }
- }
- throw e;
- }
- logger.debug("Flushing");
- this.socket.getOutputStream().flush();
- if (streamConfirmed) logger.debug("At this point, the entire " + bytes.length + "-bytes message has been streamed out successfully through the SSL connection");
-
- success = true;
- logger.debug("Notification sent on " + notification.getLatestTransmissionAttempt());
- notification.setTransmissionCompleted(true);
-
- } catch (IOException e) {
- // throw exception if we surpassed the valid number of retry attempts
- if (notification.getTransmissionAttempts() >= retryAttempts) {
- logger.error("Attempt to send Notification failed and beyond the maximum number of attempts permitted");
- notification.setTransmissionCompleted(false);
- notification.setException(e);
- logger.error("Delivery error", e);
- throw e;
-
- } else {
- logger.info("Attempt failed (" + e.getMessage() + ")... trying again");
- //Try again
- try {
- this.socket.close();
- } catch (Exception e2) {
- // do nothing
- }
- this.socket = connectionToAppleServer.getSSLSocket();
- if (socketTimeout > 0) this.socket.setSoTimeout(socketTimeout);
- }
- }
- }
- } catch (CommunicationException e) {
- throw e;
- } catch (Exception ex) {
-
- notification.setException(ex);
- logger.error("Delivery error: " + ex);
- try {
- if (closeAfter) {
- logger.error("Closing connection after error");
- stopConnection();
- }
- } catch (Exception e) {
- }
- }
- }
我也看到这段代码了。确实是有重发功能,默认重发次数是3次。请教下楼主@ autumnrain_zgq 跟你写的这个方法比有哪些需要注意的地方?
这个代码正常情况下没有问题,遇到无效的deviceToken就无法重新发送信息了,还有,他不是批量提交信息的,
rock 写道
PushQueue支持重连,
源码:
Java代码
- private void sendNotification(PushedNotification notification, boolean closeAfter) throws CommunicationException {
- try {
- Device device = notification.getDevice();
- Payload payload = notification.getPayload();
- try {
- payload.verifyPayloadIsNotEmpty();
- } catch (IllegalArgumentException e) {
- throw new PayloadIsEmptyException();
- } catch (Exception e) {
- }
-
- if (notification.getIdentifier() <= 0) notification.setIdentifier(newMessageIdentifier());
- if (!pushedNotifications.containsKey(notification.getIdentifier())) pushedNotifications.put(notification.getIdentifier(), notification);
- int identifier = notification.getIdentifier();
-
- String token = device.getToken();
- // even though the BasicDevice constructor validates the token, we revalidate it in case we were passed another implementation of Device
- BasicDevice.validateTokenFormat(token);
- // PushedNotification pushedNotification = new PushedNotification(device, payload);
- byte[] bytes = getMessage(token, payload, identifier, notification);
- // pushedNotifications.put(pushedNotification.getIdentifier(), pushedNotification);
-
- /* Special simulation mode to skip actual streaming of message */
- boolean simulationMode = payload.getExpiry() == 919191;
-
- boolean success = false;
-
- BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
- int socketTimeout = getSslSocketTimeout();
- if (socketTimeout > 0) this.socket.setSoTimeout(socketTimeout);
- notification.setTransmissionAttempts(0);
- // Keep trying until we have a success
- while (!success) {
- try {
- logger.debug("Attempting to send notification: " + payload.toString() + "");
- logger.debug(" to device: " + token + "");
- notification.addTransmissionAttempt();
- boolean streamConfirmed = false;
- try {
- if (!simulationMode) {
- this.socket.getOutputStream().write(bytes);
- streamConfirmed = true;
- } else {
- logger.debug("* Simulation only: would have streamed " + bytes.length + "-bytes message now..");
- }
- } catch (Exception e) {
- if (e != null) {
- if (e.toString().contains("certificate_unknown")) {
- throw new InvalidCertificateChainException(e.getMessage());
- }
- }
- throw e;
- }
- logger.debug("Flushing");
- this.socket.getOutputStream().flush();
- if (streamConfirmed) logger.debug("At this point, the entire " + bytes.length + "-bytes message has been streamed out successfully through the SSL connection");
-
- success = true;
- logger.debug("Notification sent on " + notification.getLatestTransmissionAttempt());
- notification.setTransmissionCompleted(true);
-
- } catch (IOException e) {
- // throw exception if we surpassed the valid number of retry attempts
- if (notification.getTransmissionAttempts() >= retryAttempts) {
- logger.error("Attempt to send Notification failed and beyond the maximum number of attempts permitted");
- notification.setTransmissionCompleted(false);
- notification.setException(e);
- logger.error("Delivery error", e);
- throw e;
-
- } else {
- logger.info("Attempt failed (" + e.getMessage() + ")... trying again");
- //Try again
- try {
- this.socket.close();
- } catch (Exception e2) {
- // do nothing
- }
- this.socket = connectionToAppleServer.getSSLSocket();
- if (socketTimeout > 0) this.socket.setSoTimeout(socketTimeout);
- }
- }
- }
- } catch (CommunicationException e) {
- throw e;
- } catch (Exception ex) {
-
- notification.setException(ex);
- logger.error("Delivery error: " + ex);
- try {
- if (closeAfter) {
- logger.error("Closing connection after error");
- stopConnection();
- }
- } catch (Exception e) {
- }
- }
- }
我也看到这段代码了。确实是有重发功能,默认重发次数是3次。请教下楼主@ autumnrain_zgq 跟你写的这个方法比有哪些需要注意的地方?
sorehead 写道
autumnrain_zgq 写道
sorehead 写道
楼主可以贴一份完整的代码吗,我也在纠结这个问题。
下载下来JavaAPNS源代码项目,在PushNotificationManager这个类中增加我文章中增加的那个方法就可以了。其它地方我也没有改的,
this.createNewSocket(); 都做了些什么事情?只是重新建立一个socket连接吗?方便贴出这个方法吗?
Java代码
- public void createNewSocket() throws SocketException, KeystoreException, CommunicationException {
- logger.info(psn + "创建新的Socke的连接");
- if (this.socket != null) {
- try {
- socket.close();
- } catch (Exception e) {
- logger.info("关闭Socket连接时出错...", e);
- }
- }
- this.socket = connectionToAppleServer.getSSLSocket();
- this.socket.setSoTimeout(3000);
- this.socket.setKeepAlive(true);
- }
autumnrain_zgq 写道
sorehead 写道
楼主可以贴一份完整的代码吗,我也在纠结这个问题。
下载下来JavaAPNS源代码项目,在PushNotificationManager这个类中增加我文章中增加的那个方法就可以了。其它地方我也没有改的,
this.createNewSocket(); 都做了些什么事情?只是重新建立一个socket连接吗?方便贴出这个方法吗?
sorehead 写道
楼主可以贴一份完整的代码吗,我也在纠结这个问题。
下载下来JavaAPNS源代码项目,在PushNotificationManager这个类中增加我文章中增加的那个方法就可以了。其它地方我也没有改的,
PushQueue支持重连,
源码:
Java代码
- private void sendNotification(PushedNotification notification, boolean closeAfter) throws CommunicationException {
- try {
- Device device = notification.getDevice();
- Payload payload = notification.getPayload();
- try {
- payload.verifyPayloadIsNotEmpty();
- } catch (IllegalArgumentException e) {
- throw new PayloadIsEmptyException();
- } catch (Exception e) {
- }
-
- if (notification.getIdentifier() <= 0) notification.setIdentifier(newMessageIdentifier());
- if (!pushedNotifications.containsKey(notification.getIdentifier())) pushedNotifications.put(notification.getIdentifier(), notification);
- int identifier = notification.getIdentifier();
-
- String token = device.getToken();
- // even though the BasicDevice constructor validates the token, we revalidate it in case we were passed another implementation of Device
- BasicDevice.validateTokenFormat(token);
- // PushedNotification pushedNotification = new PushedNotification(device, payload);
- byte[] bytes = getMessage(token, payload, identifier, notification);
- // pushedNotifications.put(pushedNotification.getIdentifier(), pushedNotification);
-
- /* Special simulation mode to skip actual streaming of message */
- boolean simulationMode = payload.getExpiry() == 919191;
-
- boolean success = false;
-
- BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
- int socketTimeout = getSslSocketTimeout();
- if (socketTimeout > 0) this.socket.setSoTimeout(socketTimeout);
- notification.setTransmissionAttempts(0);
- // Keep trying until we have a success
- while (!success) {
- try {
- logger.debug("Attempting to send notification: " + payload.toString() + "");
- logger.debug(" to device: " + token + "");
- notification.addTransmissionAttempt();
- boolean streamConfirmed = false;
- try {
- if (!simulationMode) {
- this.socket.getOutputStream().write(bytes);
- streamConfirmed = true;
- } else {
- logger.debug("* Simulation only: would have streamed " + bytes.length + "-bytes message now..");
- }
- } catch (Exception e) {
- if (e != null) {
- if (e.toString().contains("certificate_unknown")) {
- throw new InvalidCertificateChainException(e.getMessage());
- }
- }
- throw e;
- }
- logger.debug("Flushing");
- this.socket.getOutputStream().flush();
- if (streamConfirmed) logger.debug("At this point, the entire " + bytes.length + "-bytes message has been streamed out successfully through the SSL connection");
-
- success = true;
- logger.debug("Notification sent on " + notification.getLatestTransmissionAttempt());
- notification.setTransmissionCompleted(true);
-
- } catch (IOException e) {
- // throw exception if we surpassed the valid number of retry attempts
- if (notification.getTransmissionAttempts() >= retryAttempts) {
- logger.error("Attempt to send Notification failed and beyond the maximum number of attempts permitted");
- notification.setTransmissionCompleted(false);
- notification.setException(e);
- logger.error("Delivery error", e);
- throw e;
-
- } else {
- logger.info("Attempt failed (" + e.getMessage() + ")... trying again");
- //Try again
- try {
- this.socket.close();
- } catch (Exception e2) {
- // do nothing
- }
- this.socket = connectionToAppleServer.getSSLSocket();
- if (socketTimeout > 0) this.socket.setSoTimeout(socketTimeout);
- }
- }
- }
- } catch (CommunicationException e) {
- throw e;
- } catch (Exception ex) {
-
- notification.setException(ex);
- logger.error("Delivery error: " + ex);
- try {
- if (closeAfter) {
- logger.error("Closing connection after error");
- stopConnection();
- }
- } catch (Exception e) {
- }
- }
- }
鐜嬫旦 写道
鐜嬫旦 写道
pns 2.2版本不是支持群发嘛?
楼主,看到尽快回复下,,最近也在整这个
你好,是不支持群发的,群发的情况下,是在一个连接打开的情况下,持续写入数据,遇到无效的deviceToken苹果会断开连接,并返回相应的消息编号,这时需要重新连接,再次发送数据。博文的代码中这是这样实现的,
鐜嬫旦 写道
pns 2.2版本不是支持群发嘛?
楼主,看到尽快回复下,,最近也在整这个
linbaoji 写道
请问你的 JavaPNS 版本是什么 啊!??
谢谢1
你好,我查看一下,版本是:2.2
请问你的 JavaPNS 版本是什么 啊!??
谢谢1