모바일 서비스를 하기 위해서는 서버 또는 외부에서 정해진 스케쥴에 의해 푸시를 발송하는 경우가 빈번합니다. 요즘은 클라우드 서비스를 비롯하여 Facebook 에서도 약간의 비용을 받고 푸시 발송 솔루션을 제공하는데요.. 굳이 외부 솔루션을 사용하지 않고 직접 Push 서비스를 구축할 수 있는 오픈 라이브러리를 소개합니다. 간단한 사용으로 푸시의 모든 기능을 손쉽게 구축할 수 있는 매력적인 솔루션입니다.



1. APNS 발송 처리 부분
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration (ApnsConfiguration.ApnsServerEnvironment.Sandbox, 
    "push-cert.p12", "push-cert-pwd");

// Create a new broker
var apnsBroker = new ApnsServiceBroker (config);

// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {

    aggregateEx.Handle (ex => {

        // See what kind of exception it was to further diagnose
        if (ex is ApnsNotificationException) {
            var notificationException = (ApnsNotificationException)ex;

            // Deal with the failed notification
            var apnsNotification = notificationException.Notification;
            var statusCode = notificationException.ErrorStatusCode;

            Console.WriteLine ($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");

        } else {
            // Inner exception might hold more useful information like an ApnsConnectionException           
            Console.WriteLine ($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
        }

        // Mark it as handled
        return true;
    });
};

apnsBroker.OnNotificationSucceeded += (notification) => {
    Console.WriteLine ("Apple Notification Sent!");
};

// Start the broker
apnsBroker.Start ();

foreach (var deviceToken in MY_DEVICE_TOKENS) {
    // Queue a notification to send
    apnsBroker.QueueNotification (new ApnsNotification {
        DeviceToken = deviceToken,
        Payload = JObject.Parse ("{\"aps\":{\"badge\":7}}")
    });
}

// Stop the broker, wait for it to finish   
// This isn't done after every message, but after you're
// done with the broker
apnsBroker.Stop ();



APNS 발송 처리시 더 이상 유효하지 않은 단말의 토큰을 Feedback 서비스를 통해 삭제하는 작업을 별도로 진행해 줘야만 합니다.

2. APNS Feedback 처리
var config = new ApnsConfiguration (
    ApnsConfiguration.ApnsServerEnvironment.Sandbox, 
    Settings.Instance.ApnsCertificateFile, 
    Settings.Instance.ApnsCertificatePassword);

var fbs = new FeedbackService (config);
fbs.FeedbackReceived += (string deviceToken, DateTime timestamp) => {
    // Remove the deviceToken from your database
    // timestamp is the time the token was reported as expired
};
fbs.Check ();



GCM 의 경우 발송 처리시에 유효하지 않은 단말이라는 결과를 전달 해 줌으로 한 번의 작업으로 깔끔하게 마무리 할 수 있습니다.

3. GCM Push 처리

// Configuration
var config = new GcmConfiguration ("GCM-SENDER-ID", "AUTH-TOKEN", null);

// Create a new broker
var gcmBroker = new GcmServiceBroker (config);

// Wire up events
gcmBroker.OnNotificationFailed += (notification, aggregateEx) => {

    aggregateEx.Handle (ex => {

        // See what kind of exception it was to further diagnose
        if (ex is GcmNotificationException) {
            var notificationException = (GcmNotificationException)ex;

            // Deal with the failed notification
            var gcmNotification = notificationException.Notification;
            var description = notificationException.Description;

            Console.WriteLine ($"GCM Notification Failed: ID={gcmNotification.MessageId}, Desc={description}");
        } else if (ex is GcmMulticastResultException) {
            var multicastException = (GcmMulticastResultException)ex;

            foreach (var succeededNotification in multicastException.Succeeded) {
                Console.WriteLine ($"GCM Notification Failed: ID={succeededNotification.MessageId}");
            }

            foreach (var failedKvp in multicastException.Failed) {
                var n = failedKvp.Key;
                var e = failedKvp.Value;

                Console.WriteLine ($"GCM Notification Failed: ID={n.MessageId}, Desc={e.Description}");
            }

        } else if (ex is DeviceSubscriptionExpiredException) {
            var expiredException = (DeviceSubscriptionExpiredException)ex;

            var oldId = expiredException.OldSubscriptionId;
            var newId = expiredException.NewSubscriptionId;

            Console.WriteLine ($"Device RegistrationId Expired: {oldId}");

            if (!string.IsNullOrWhitespace (newId)) {
                // If this value isn't null, our subscription changed and we should update our database
                Console.WriteLine ($"Device RegistrationId Changed To: {newId}");
            }
        } else if (ex is RetryAfterException) {
            var retryException = (RetryAfterException)ex;
            // If you get rate limited, you should stop sending messages until after the RetryAfterUtc date
            Console.WriteLine ($"GCM Rate Limited, don't send more until after {retryException.RetryAfterUtc}");
        } else {
            Console.WriteLine ("GCM Notification Failed for some unknown reason");
        }

        // Mark it as handled
        return true;
    });
};

gcmBroker.OnNotificationSucceeded += (notification) => {
    Console.WriteLine ("GCM Notification Sent!");
};

// Start the broker
gcmBroker.Start ();

foreach (var regId in MY_REGISTRATION_IDS) {
    // Queue a notification to send
    gcmBroker.QueueNotification (new GcmNotification {
        RegistrationIds = new List { 
            regId
        },
        Data = JObject.Parse ("{ \"somekey\" : \"somevalue\" }")
    });
}

// Stop the broker, wait for it to finish   
// This isn't done after every message, but after you're
// done with the broker
gcmBroker.Stop ();
공식 다운로드는 이 곳에서 하시면 됩니다. https://github.com/Redth/PushSharp

'IT 이야기 > Code' 카테고리의 다른 글

고성능 .NET코드 프로그래밍 <책소개>  (0) 2016.11.08
Open source vs Commercial software - 1부  (0) 2015.05.27

+ Recent posts