Android Push Server & MQTT

광운 이
광운 이Developer at Coupang
Android Push Server
                          &
                        MQTT


                             ultrakain@gmail.com
                                         이광운
13년 1월 28일 월요일
Mobile Push Notification Service

      ● Google - GCM (Google Cloud Message), C2DM

      ● Apple - APNS (Apple Push Notification Service)

      ● MS - MPNS (Microsoft Push Notification Service)

      ● SKT - Smart Push(AlwaysOn Management framework)

      ● 기타...




13년 1월 28일 월요일
Android Push Notification Service

      ● GCM (Google Cloud Message)

           - Getting Started :

           http://developer.android.com/google/gcm/gs.html

      ● Private Push Service

           - 각 서비스/업체별로 구현한 Push Service




13년 1월 28일 월요일
Naver Npush
                      SKT AOM
                      Kakatok
                      Facebook Messenger
                      Viber
                      NateOn
                      기타

                 이미지 출처 : http://helloworld.naver.com/helloworld/1846

13년 1월 28일 월요일
Why Private Push Service ?

       ● C2DM시절 Push의 낮은 신뢰도 (속도, 도달률)

       ● Google의 전송량 제한

       ● Android 2.2 이상 ( Froyo )

       ● 구글 계정으로 로그인해야 사용 가능

       ● 자체 Customizable Business Rules 구현 필요




13년 1월 28일 월요일
PUSH 구현 방식 - Push & Pull

      ● Push - 지속적인 연결 유지

           Server -> Client

      ● Pull - 지속적인 Polling으로 데이타 갱신 ( 카카오톡)

           Client -> Server

      ● 차이점

           - 정보의 주도권

           - 배터리, 패킷 소모량

13년 1월 28일 월요일
Push Service 구현 = Server <- (protocol) -> Client

      ● MQTT

      ● XMPP

      ● HTTP

      ● Custom Protocol




    MQTT = MQ Telemetry Transport
    XMPP = Extensible Messaging and Presence Protocol
    HTTP = HyperText Transfer Protocol

13년 1월 28일 월요일
XMPP (5222)

      * XML 기반

      * 원래 이름은 Jabber

      * Jabber 오픈소스 커뮤니티 1999년

      * 국제 인터넷 표준화 기구 - 개방형 표준

      * IM, 채팅

      * Google Talk, Google App Engine 제공

      * BOSH : JavaScript, Firewall
                                BOSH : Bidirectional-streams Over Synchronous HTTP

13년 1월 28일 월요일
XMPP 메시지 형태

      Stream
        <stream:stream from="[server]" id="[unique ID over conversation]"
        xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0">



       Message
       <message from="sendinguser@somedomain"
                to="recipient@somedomain" xml:lang='en'>
         <body>
           Body of message
         </body>
       </message>




             http://www.ibm.com/developerworks/kr/xml/tutorials/x-realtimeXMPPtut/section3.html

13년 1월 28일 월요일
MQTT (1883)
       * IBM과 Eurotech(Arcom)에 의해 1999년 최초 개발

       * 센서, 원격 검침 영역 , 모바일기기, 아두이노

            Low bandwidth, High latency, Unreliable, High cost

       * Clinet lib: C 버전 30Kb, Java 버전 100Kb 내외

       * Publish/Subscribe, QoS 제공 (0, 1, 2)

       * Openly published with a royalty-free license

       * minimal 2byte, 가변길이


13년 1월 28일 월요일
MQTT 메시지 형태



       Reserved - Reserved
       CONNECT - Client request to connect to Server
       CONNACK - Connect Acknowledgment
       PUBLISH - Publish message
       PUBACK - Publish Acknowledgment
       PUBREC - Publish Received (assured delivery part 1)
       PUBREL - Publish Release (assured delivery part 2)
       PUBCOMP - Publish Complete (assured delivery part 3)
       SUBSCRIBE - Client Subscribe request
       SUBACK - Subscribe Acknowledgment
       UNSUBSCRIBE - Client Unsubscribe request
       UNSUBACK - Unsubscribe Acknowledgment
       PINGREQ - PING Request
       PINGRESP - PING Response
       DISCONNECT - Client is Disconnecting
       Reserved - Reserved


      MQTT Spec v3.1 :
      http://www.ibm.com/developerworks/webservices/library/ws-mqtt/index.html
      http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/MQTT_V3.1_Protocol_Specific.pdf
13년 1월 28일 월요일
http://stephendnicholas.com/archives/1217



13년 1월 28일 월요일
Facebook

   페이스북 엔지니어링 블로그 : http:/            /goo.gl/o1WGo
   페이스북 메신저 앱 : http:/       /goo.gl/OfMer, http:/ /goo.gl/9RQhP
   NHN Helloworld Blog : http://helloworld.naver.com/helloworld/1846

13년 1월 28일 월요일
MQTT

13년 1월 28일 월요일
Private Push Service POC


         * 서버 : RSMB, Mosquitto, etc...

         * 클라이언트 : Console, Web, Android Emul & Phone




13년 1월 28일 월요일
MQTT Server - OpenSource

       * IBM RSMB (Really Small Message Broker)
       * Mosquitto (test.mosquitto.org)
       * IBM WebSphere MQ Telemetry
       * MQTT.js (Node.js)
       * eMQTT (Erlang)
       * RabbitMQ
       * Apache ActiveMQ
       * Apache Apollo
       * Moquette (Apache MINA)



                          http://mqtt.org/software

13년 1월 28일 월요일
MQTT Client - OpenSource
       *   Device-specific
       *   ActionScript
       *   C / C++
       *   C#
       *   Dephi
       *   Erlang
       *   Java
       *   JavaScript / Node.js
       *   .NET
       *   Object-c
       *   Perl
       *   PHP
       *   Python
       *   REXX
       *   Ruby            http://mqtt.org/software

13년 1월 28일 월요일
Private Push Server 선택




                           출처 : http://mqtt.org/wiki/doku.php/server_support


13년 1월 28일 월요일
Mosquitto Sample




13년 1월 28일 월요일
솔루션을 만들어
                  팔 수 있을까?



13년 1월 28일 월요일
Mosquitto - 1차 테스트

      * Console & Mosquitto Command


      * Java Client Library



                                                                                   OK !
            * Mosquitto Java Client
            * Akka + IBM Paho Client


      * Python Client Libarry
            * python-mosquitto
            * MQTT-for-Twisted-Python
            * nyamuk

       Akka ( http://akka.io )

       - Build powerful concurrent & distributed applications more easily. on the JVM

13년 1월 28일 월요일
Mosquitto - 2차 성능 테스트
       * 서버 1대
            * CentOS 5.5
            * Mosquitto 1 프로세스
                                          6500
       * 클라이언트                                    6500
            * 맥북 프로 2대 + iMac 1대
            * 각 6500개 Python Client
            * ipTime 공유기 n700           공유기         6500




                                      mosquitto
                       console
                                       broker

13년 1월 28일 월요일
Mosquitto - 2차 결과

      - 약 2만개 Python MQTT Client 안정적 접속 (2.5일간 유지)
      - CPU : 단일 코어 사용
      - 메모리는 Client 수와 상관없이 일정하게 유지
      - 연결 유지를 위한 Ping Req/Res의 트래픽 : 별도 전용선
      - Publish Time 5초 ~ 6초 ( 이유는 ipTime 공유기의 한계 - 속도 지연)




                         OK !
13년 1월 28일 월요일
알게 된 것 1 : 별도의 전용 Line을 통한 서비스
        알게 된 것 2 : Default FD <= 1024




13년 1월 28일 월요일
import mosquitto

                      def on_connect(mosq, obj, rc):
                          print("rc: "+str(rc))

                      def on_message(mosq, obj, msg):
                          print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

                      def on_publish(mosq, obj, mid):
                          print("mid: "+str(mid))

                      def on_subscribe(mosq, obj, mid, granted_qos):
                          print("Subscribed: "+str(mid)+" "+str(granted_qos))

                      def on_log(mosq, obj, level, string):
                          print(string)

                      # If you want to use a specific client id, use
                      # mqttc = mosquitto.Mosquitto("client-id")
                      # but note that the client id must be unique on the broker. Leaving the
                      client
                      # id parameter empty will generate a random id for you.
                      mqttc = mosquitto.Mosquitto()
                      mqttc.on_message = on_message
                      mqttc.on_connect = on_connect
                      mqttc.on_publish = on_publish
                      mqttc.on_subscribe = on_subscribe
                      # Uncomment to enable debug messages
                      #mqttc.on_log = on_log
                      mqttc.connect("test.mosquitto.org", 1883, 60)
                      mqttc.subscribe("$SYS/#", 0)



                      rc = 0
                      while rc == 0:
                          rc = mqttc.loop()

                      print("rc: "+str(rc))




      https://bitbucket.org/oojah/mosquitto/src/tip/lib/python/sub.py

13년 1월 28일 월요일
Default 1024




                           Error
            filedescriptor out of range in select()




13년 1월 28일 월요일
Mosquitto Python MQTT Client




                  select? mysql select?



13년 1월 28일 월요일
Python IO

         * select
           - The first three arguments are sequences of
             ‘waitable objects’: either integers representing
             file descriptors
         * kqueue
           - kernel event notification mechanism
         * kevent
           - Returns a kernel event object
         * poll
           - better scalability for network servers
             that service many, many clients
             at the same time
         * epoll
           - Returns an edge polling object, which can be used as Edge or
             Level Triggered interface for I/O events




13년 1월 28일 월요일
MQTT-For-Twisted-Python
       https://github.com/adamvr/MQTT-For-Twisted-Python/blob/master/MQTT.py




       MQTT4PythonTwistedDemo
       https://code.google.com/p/beaglebone-iot/wiki/MQTT4PythonTwistedDemo



       from twisted.internet import kqreactor
       kqreactor.install()

       ....

       if __name__ == '__main__':

              mqttMessageBuffer = []

              clientCountRange = range(1, 1200)
              for r in clientCountRange:
                  try:
                      mqttFactory = MQTTListenerFactory()
                      reactor.connectTCP("192.168.10.32", 1883, mqttFactory)
                  except:
                      log.msg("except " + sys.exec_info())

              reactor.run()


13년 1월 28일 월요일
What is Twisted?

       Twisted is an event-driven networking engine written in Python


        from twisted.internet import protocol, reactor

        class Echo(protocol.Protocol):
            def dataReceived(self, data):
                self.transport.write(data)

        class EchoFactory(protocol.Factory):
            def buildProtocol(self, addr): twisted.web import server, resource
                                      from
                return Echo()         from twisted.internet import reactor

                                      class HelloResource(resource.Resource):
        reactor.listenTCP(1234, EchoFactory())
                                          isLeaf = True
        reactor.run()                     numberRequests = 0

                                            def render_GET(self, request):
                                                self.numberRequests += 1
                                                request.setHeader("content-type", "text/plain")
                                                return "I am request #" +
                                        str(self.numberRequests) + "n"

                                        reactor.listenTCP(8080, server.Site(HelloResource()))
                                        reactor.run()




13년 1월 28일 월요일
Twisted Document - Reactor
        Reactor Overview
          1. Reactor Basics
          2. Using the reactor object
        This HOWTO introduces the Twisted reactor, describes the basics of the reactor and links to the various reactor interfaces.

        Reactor Basics
        The reactor is the core of the event loop within Twisted -- the loop which drives applications using Twisted. The event loop is a programming construct that waits for
        and dispatches events or messages in a program. It works by calling some internal or external "event provider", which generally blocks until an event has arrived,
        and then calls the relevant event handler ("dispatches the event"). The reactor provides basic interfaces to a number of services, including network
        communications, threading, and event dispatching.




        Choosing a Reactor and GUI Toolkit Integration
          1.   Overview
          2.   Reactor Functionality
          3.   General Purpose Reactors
                 ◦    Select()-based Reactor
          4.   Platform-Specific Reactors
                 ◦    Poll-based Reactor
                 ◦    KQueue
                 ◦    WaitForMultipleObjects (WFMO) for Win32
                 ◦    Input/Output Completion Port (IOCP) for Win32
                 ◦    Epoll-based Reactor
          5.   GUI Integration Reactors
                 ◦    GTK+
                 ◦    wxPython
                 ◦    CoreFoundation
          6.   Non-Reactor GUI Integration
                 ◦    Tkinter
                 ◦    PyUI




13년 1월 28일 월요일
Reactor Pattern?
        The reactor design pattern is an event handling pattern for handling service
        requests delivered concurrently to a service handler by one or more inputs.
        The service handler then demultiplexes the incoming requests and dispatches
        them synchronously to the associated request handlers

        All reactor systems are single threaded by definition, but can exist in a
        multithreaded environment.


        C - libevent
        C++ - POCO C++ Libraries
        Java - Apache MINA, JBoss Netty, Apache Cocoon, Disruptor
        JavaScript - Node.js
        Perl - POE
        Python - Twisted
        Ruby - EventMachine


         http://en.wikipedia.org/wiki/Reactor_pattern

13년 1월 28일 월요일
POSA 2
       Patterns for Concurrent and Networked Objects




        이미지 출처 : http://www.cs.wustl.edu/~schmidt/POSA/POSA2/


13년 1월 28일 월요일
Opps !




        이미지 출처 : http://goo.gl/HUiFZ


13년 1월 28일 월요일
만드는 이유?

      * 기업 => Push 마케팅 Tool

      * 기업 기간계 시스템 연동 : 보험, 증권, 은행, 쇼핑몰

           => SMS/MMS = 비용

      * 기업 자신들의 모바일 앱 고객 분석




13년 1월 28일 월요일
기업 개발 부서 반응

      * 이런 걸 왜 사?

      * 내가 이틀이면 만들겠다 = 자체 개발? => 몇 달 뒤 전화 옴

      * 발송만 보면 이틀이 아니라 몇 시간 내에 가능 => 맞는 말

      * 그러나 기업 자체 개발 인력 부족, 자체 문제 및 요구사항

      * History : 메일 = PUSH




13년 1월 28일 월요일
헉 !!!




      http://count.ly/
      https://github.com/Countly                  node.js, mongodb, nginx
      https://github.com/isaacs/node-supervisor
      http:/
      http:/
            /countly.firejune.io/login
            /goo.gl/U63L1
                                                    supervisor, python
13년 1월 28일 월요일
정리

       * Private Push Server 구축은 어렵지 않게 시작 할 수 있다.

       * 이를 구축하는데 MQTT 좋은 선택

       * Python IO Server/Client => twisted 시작

       * 국내 Push 독보적인 솔루션 없음 => 메일 시장 History 반복




13년 1월 28일 월요일
최종 보스




    이미지 출처 : http://goo.gl/NF18A

13년 1월 28일 월요일
감사합니다.




13년 1월 28일 월요일
* 참고
       * 모바일 Push와 nPush - http:/       /helloworld.naver.com/helloworld/1119
       * Android PUSH와 카카오톡 사건 - http:/           /mobizen.pe.kr/1074
       * 3G에 대한 이해 - http:/       /helloworld.naver.com/helloworld/111111
       * C500k - http:/ /www.mimul.com/pebble/default/2012/07/18/1342602654675.html
       * 어반 에어쉽 Architecture - http:/       /www.slideshare.net/eonnen/from-100s-to-100s-of-millions
       * MQTT
          * Test Server - http:/ /test.mosquitto.org/
          * http://www.slideshare.net/andypiper/introducing-mqtt
          * ftp://public.dhe.ibm.com/software/kr/ik2012/mqtt.pdf
          * 활용 : http:/   /mqtt.org/wiki/doku.php/example_uses
          * http://stephendnicholas.com/archives/1217
       * XMPP
          * Google App Engine - http:/   /goo.gl/lXHcM
          * Android Push - http:/  /blog.softwaregeeks.org/archives/530
          * http://blog.doortts.com/148
          * IBM 웹기반 알림 - http:/        /goo.gl/O8UEy
       * POSA 2 무료 강좌 - http:/       /www.devpia.com/NET2/EvaCast/Lecture/?fCode=1&sCode=2&c=4




13년 1월 28일 월요일
1 of 41

Recommended

Google jib: Building Java containers without Docker by
Google jib: Building Java containers without DockerGoogle jib: Building Java containers without Docker
Google jib: Building Java containers without DockerMaarten Smeets
464 views20 slides
MIO Prediction Engine(仮) with モブキャスト on GCP by
MIO Prediction Engine(仮) with モブキャスト on GCPMIO Prediction Engine(仮) with モブキャスト on GCP
MIO Prediction Engine(仮) with モブキャスト on GCPIzumi Akiyama
38.7K views38 slides
안정적인 서비스 운영 2014.03 by
안정적인 서비스 운영   2014.03안정적인 서비스 운영   2014.03
안정적인 서비스 운영 2014.03Changyol BAEK
72.2K views84 slides
Optimizing {Java} Application Performance on Kubernetes by
Optimizing {Java} Application Performance on KubernetesOptimizing {Java} Application Performance on Kubernetes
Optimizing {Java} Application Performance on KubernetesDinakar Guniguntala
421 views15 slides
AWS Black Belt Tech シリーズ 2015 - AWS CodeCommit & AWS CodePipeline & AWS CodeD... by
AWS Black Belt Tech シリーズ 2015 - AWS CodeCommit & AWS CodePipeline & AWS CodeD...AWS Black Belt Tech シリーズ 2015 - AWS CodeCommit & AWS CodePipeline & AWS CodeD...
AWS Black Belt Tech シリーズ 2015 - AWS CodeCommit & AWS CodePipeline & AWS CodeD...Amazon Web Services Japan
107.4K views72 slides
AWS SAMで始めるサーバーレスアプリケーション開発 by
AWS SAMで始めるサーバーレスアプリケーション開発AWS SAMで始めるサーバーレスアプリケーション開発
AWS SAMで始めるサーバーレスアプリケーション開発真吾 吉田
43.1K views52 slides

More Related Content

What's hot

Envoy 를 이용한 코드 배포 자동화 by
Envoy 를 이용한 코드 배포 자동화Envoy 를 이용한 코드 배포 자동화
Envoy 를 이용한 코드 배포 자동화Juwon Kim
6.3K views23 slides
AWS における サーバーレスの基礎からチューニングまで by
AWS における サーバーレスの基礎からチューニングまでAWS における サーバーレスの基礎からチューニングまで
AWS における サーバーレスの基礎からチューニングまで崇之 清水
4.7K views72 slides
AWS Black Belt Techシリーズ Amazon Kinesis by
AWS Black Belt Techシリーズ  Amazon KinesisAWS Black Belt Techシリーズ  Amazon Kinesis
AWS Black Belt Techシリーズ Amazon KinesisAmazon Web Services Japan
19.7K views97 slides
How to build massive service for advance by
How to build massive service for advanceHow to build massive service for advance
How to build massive service for advanceDaeMyung Kang
13.2K views90 slides
‘서울 어린이 대공원’의 기간별 주차장 이용 현황 분석 by
‘서울 어린이 대공원’의 기간별 주차장 이용 현황 분석‘서울 어린이 대공원’의 기간별 주차장 이용 현황 분석
‘서울 어린이 대공원’의 기간별 주차장 이용 현황 분석Hyejeong Song
222 views19 slides
Amazon Aurora 100% 활용하기 by
Amazon Aurora 100% 활용하기Amazon Aurora 100% 활용하기
Amazon Aurora 100% 활용하기Amazon Web Services Korea
14K views53 slides

What's hot(20)

Envoy 를 이용한 코드 배포 자동화 by Juwon Kim
Envoy 를 이용한 코드 배포 자동화Envoy 를 이용한 코드 배포 자동화
Envoy 를 이용한 코드 배포 자동화
Juwon Kim6.3K views
AWS における サーバーレスの基礎からチューニングまで by 崇之 清水
AWS における サーバーレスの基礎からチューニングまでAWS における サーバーレスの基礎からチューニングまで
AWS における サーバーレスの基礎からチューニングまで
崇之 清水4.7K views
How to build massive service for advance by DaeMyung Kang
How to build massive service for advanceHow to build massive service for advance
How to build massive service for advance
DaeMyung Kang13.2K views
‘서울 어린이 대공원’의 기간별 주차장 이용 현황 분석 by Hyejeong Song
‘서울 어린이 대공원’의 기간별 주차장 이용 현황 분석‘서울 어린이 대공원’의 기간별 주차장 이용 현황 분석
‘서울 어린이 대공원’의 기간별 주차장 이용 현황 분석
Hyejeong Song222 views
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기 by NAVER D2
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기
NAVER D22.5K views
[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현 by NAVER Engineering
[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현
[네이버오픈소스세미나] Pinpoint를 이용해서 서버리스 플랫폼 Apache Openwhisk 트레이싱하기 - 오승현
NAVER Engineering7.4K views
DockerでCKANを動かそう by Takayuki Goto
DockerでCKANを動かそうDockerでCKANを動かそう
DockerでCKANを動かそう
Takayuki Goto319 views
찾아가는 AWS 세미나(구로,가산,판교) - 메가존과 함께하는 클라우드 컴퓨팅 by Amazon Web Services Korea
찾아가는 AWS 세미나(구로,가산,판교) - 메가존과 함께하는 클라우드 컴퓨팅찾아가는 AWS 세미나(구로,가산,판교) - 메가존과 함께하는 클라우드 컴퓨팅
찾아가는 AWS 세미나(구로,가산,판교) - 메가존과 함께하는 클라우드 컴퓨팅
Introducing Confluent labs Parallel Consumer client | Anthony Stubbes, Confluent by HostedbyConfluent
Introducing Confluent labs Parallel Consumer client | Anthony Stubbes, ConfluentIntroducing Confluent labs Parallel Consumer client | Anthony Stubbes, Confluent
Introducing Confluent labs Parallel Consumer client | Anthony Stubbes, Confluent
HostedbyConfluent3.3K views
ElastiCache Deep Dive: Design Patterns for In-Memory Data Stores (DAT302-R1) ... by Amazon Web Services
ElastiCache Deep Dive: Design Patterns for In-Memory Data Stores (DAT302-R1) ...ElastiCache Deep Dive: Design Patterns for In-Memory Data Stores (DAT302-R1) ...
ElastiCache Deep Dive: Design Patterns for In-Memory Data Stores (DAT302-R1) ...
Amazon Web Services2.6K views
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안 by SANG WON PARK
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
SANG WON PARK15.2K views
Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019 by confluent
Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019
Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019
confluent3.9K views
AzureDevOpsで始めるAndroidのCI/CD by Shinya Nakajima
AzureDevOpsで始めるAndroidのCI/CDAzureDevOpsで始めるAndroidのCI/CD
AzureDevOpsで始めるAndroidのCI/CD
Shinya Nakajima2.4K views

Similar to Android Push Server & MQTT

Kafka slideshare by
Kafka   slideshareKafka   slideshare
Kafka slidesharewonyong hwang
369 views128 slides
Wisepush by
WisepushWisepush
Wisepush호진 하
198 views5 slides
김성윤 - 우분투로 슈퍼컴 만들기 (2011Y03M26D) by
김성윤 - 우분투로 슈퍼컴 만들기 (2011Y03M26D)김성윤 - 우분투로 슈퍼컴 만들기 (2011Y03M26D)
김성윤 - 우분투로 슈퍼컴 만들기 (2011Y03M26D)Ubuntu Korea Community
7K views67 slides
Python으로 채팅 구현하기 by
Python으로 채팅 구현하기Python으로 채팅 구현하기
Python으로 채팅 구현하기Tae Young Lee
10.9K views56 slides
[OpenStack Days Korea 2016] Track2 - How to speed up OpenStack network with P... by
[OpenStack Days Korea 2016] Track2 - How to speed up OpenStack network with P...[OpenStack Days Korea 2016] Track2 - How to speed up OpenStack network with P...
[OpenStack Days Korea 2016] Track2 - How to speed up OpenStack network with P...OpenStack Korea Community
539 views33 slides
오픈스택: 구석구석 파헤쳐보기 by
오픈스택: 구석구석 파헤쳐보기오픈스택: 구석구석 파헤쳐보기
오픈스택: 구석구석 파헤쳐보기Jaehwa Park
31K views68 slides

Similar to Android Push Server & MQTT(20)

Python으로 채팅 구현하기 by Tae Young Lee
Python으로 채팅 구현하기Python으로 채팅 구현하기
Python으로 채팅 구현하기
Tae Young Lee10.9K views
[OpenStack Days Korea 2016] Track2 - How to speed up OpenStack network with P... by OpenStack Korea Community
[OpenStack Days Korea 2016] Track2 - How to speed up OpenStack network with P...[OpenStack Days Korea 2016] Track2 - How to speed up OpenStack network with P...
[OpenStack Days Korea 2016] Track2 - How to speed up OpenStack network with P...
오픈스택: 구석구석 파헤쳐보기 by Jaehwa Park
오픈스택: 구석구석 파헤쳐보기오픈스택: 구석구석 파헤쳐보기
오픈스택: 구석구석 파헤쳐보기
Jaehwa Park31K views
w3c 2017 - WebRTC 기술 back to basic 발표자료 by 동명 최
w3c 2017 - WebRTC 기술 back to basic 발표자료w3c 2017 - WebRTC 기술 back to basic 발표자료
w3c 2017 - WebRTC 기술 back to basic 발표자료
동명 최237 views
Python socket programming by Tae Young Lee
Python socket programmingPython socket programming
Python socket programming
Tae Young Lee1.5K views
Internship backend by Yein Sim
Internship backendInternship backend
Internship backend
Yein Sim120 views
2. klaytn developer meetup #2 univ chain by 전 민규
2. klaytn developer meetup #2 univ chain2. klaytn developer meetup #2 univ chain
2. klaytn developer meetup #2 univ chain
전 민규241 views
[아이펀팩토리]2017 NDC 강연 자료_아이펀 엔진 개발 노트 by iFunFactory Inc.
[아이펀팩토리]2017 NDC 강연 자료_아이펀 엔진 개발 노트[아이펀팩토리]2017 NDC 강연 자료_아이펀 엔진 개발 노트
[아이펀팩토리]2017 NDC 강연 자료_아이펀 엔진 개발 노트
iFunFactory Inc.1.5K views
Network Project by Minho Yoo
Network ProjectNetwork Project
Network Project
Minho Yoo163 views
Block chain bidding_System by 환석 주
Block chain bidding_SystemBlock chain bidding_System
Block chain bidding_System
환석 주231 views
리눅스 소켓 프로그래밍 기초 by Yu Yongwoo
리눅스 소켓 프로그래밍 기초리눅스 소켓 프로그래밍 기초
리눅스 소켓 프로그래밍 기초
Yu Yongwoo2.4K views
파이썬+네트워크 20160210 by Yong Joon Moon
파이썬+네트워크 20160210파이썬+네트워크 20160210
파이썬+네트워크 20160210
Yong Joon Moon6.4K views
Meteor Korea DEV School 1st day by seung-hyun Park
Meteor Korea DEV School 1st dayMeteor Korea DEV School 1st day
Meteor Korea DEV School 1st day
seung-hyun Park12.8K views

Recently uploaded

AD의 TAD와 협업.pptx by
AD의 TAD와 협업.pptxAD의 TAD와 협업.pptx
AD의 TAD와 협업.pptxVisual Tech Dev
50 views24 slides
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략 by
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략Open Source Consulting
111 views25 slides
성능 테스트 by
성능 테스트성능 테스트
성능 테스트Wonjun Hwang
8 views13 slides
CES 처음 가는 분을 위한 가이드 by
CES 처음 가는 분을 위한 가이드CES 처음 가는 분을 위한 가이드
CES 처음 가는 분을 위한 가이드Minsuk Lee
650 views31 slides
컴포넌트 설계 by
컴포넌트 설계컴포넌트 설계
컴포넌트 설계Wonjun Hwang
8 views21 slides
Exploring Deep Learning Acceleration Technology Embedded in LLMs by
Exploring Deep Learning Acceleration Technology Embedded in LLMsExploring Deep Learning Acceleration Technology Embedded in LLMs
Exploring Deep Learning Acceleration Technology Embedded in LLMsTae Young Lee
26 views53 slides

Recently uploaded(7)

클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략 by Open Source Consulting
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략
클라우드 네이티브 전환 요소 및 성공적인 쿠버네티스 도입 전략
CES 처음 가는 분을 위한 가이드 by Minsuk Lee
CES 처음 가는 분을 위한 가이드CES 처음 가는 분을 위한 가이드
CES 처음 가는 분을 위한 가이드
Minsuk Lee650 views
Exploring Deep Learning Acceleration Technology Embedded in LLMs by Tae Young Lee
Exploring Deep Learning Acceleration Technology Embedded in LLMsExploring Deep Learning Acceleration Technology Embedded in LLMs
Exploring Deep Learning Acceleration Technology Embedded in LLMs
Tae Young Lee26 views
해커가 되고 싶은 자는 나에게... 정보보안 입문과 길 찾기 by Jinkyoung Kim
해커가 되고 싶은 자는 나에게... 정보보안 입문과 길 찾기해커가 되고 싶은 자는 나에게... 정보보안 입문과 길 찾기
해커가 되고 싶은 자는 나에게... 정보보안 입문과 길 찾기
Jinkyoung Kim46 views

Android Push Server & MQTT

  • 1. Android Push Server & MQTT ultrakain@gmail.com 이광운 13년 1월 28일 월요일
  • 2. Mobile Push Notification Service ● Google - GCM (Google Cloud Message), C2DM ● Apple - APNS (Apple Push Notification Service) ● MS - MPNS (Microsoft Push Notification Service) ● SKT - Smart Push(AlwaysOn Management framework) ● 기타... 13년 1월 28일 월요일
  • 3. Android Push Notification Service ● GCM (Google Cloud Message) - Getting Started : http://developer.android.com/google/gcm/gs.html ● Private Push Service - 각 서비스/업체별로 구현한 Push Service 13년 1월 28일 월요일
  • 4. Naver Npush SKT AOM Kakatok Facebook Messenger Viber NateOn 기타 이미지 출처 : http://helloworld.naver.com/helloworld/1846 13년 1월 28일 월요일
  • 5. Why Private Push Service ? ● C2DM시절 Push의 낮은 신뢰도 (속도, 도달률) ● Google의 전송량 제한 ● Android 2.2 이상 ( Froyo ) ● 구글 계정으로 로그인해야 사용 가능 ● 자체 Customizable Business Rules 구현 필요 13년 1월 28일 월요일
  • 6. PUSH 구현 방식 - Push & Pull ● Push - 지속적인 연결 유지 Server -> Client ● Pull - 지속적인 Polling으로 데이타 갱신 ( 카카오톡) Client -> Server ● 차이점 - 정보의 주도권 - 배터리, 패킷 소모량 13년 1월 28일 월요일
  • 7. Push Service 구현 = Server <- (protocol) -> Client ● MQTT ● XMPP ● HTTP ● Custom Protocol MQTT = MQ Telemetry Transport XMPP = Extensible Messaging and Presence Protocol HTTP = HyperText Transfer Protocol 13년 1월 28일 월요일
  • 8. XMPP (5222) * XML 기반 * 원래 이름은 Jabber * Jabber 오픈소스 커뮤니티 1999년 * 국제 인터넷 표준화 기구 - 개방형 표준 * IM, 채팅 * Google Talk, Google App Engine 제공 * BOSH : JavaScript, Firewall BOSH : Bidirectional-streams Over Synchronous HTTP 13년 1월 28일 월요일
  • 9. XMPP 메시지 형태 Stream <stream:stream from="[server]" id="[unique ID over conversation]" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0"> Message <message from="sendinguser@somedomain" to="recipient@somedomain" xml:lang='en'> <body> Body of message </body> </message> http://www.ibm.com/developerworks/kr/xml/tutorials/x-realtimeXMPPtut/section3.html 13년 1월 28일 월요일
  • 10. MQTT (1883) * IBM과 Eurotech(Arcom)에 의해 1999년 최초 개발 * 센서, 원격 검침 영역 , 모바일기기, 아두이노 Low bandwidth, High latency, Unreliable, High cost * Clinet lib: C 버전 30Kb, Java 버전 100Kb 내외 * Publish/Subscribe, QoS 제공 (0, 1, 2) * Openly published with a royalty-free license * minimal 2byte, 가변길이 13년 1월 28일 월요일
  • 11. MQTT 메시지 형태 Reserved - Reserved CONNECT - Client request to connect to Server CONNACK - Connect Acknowledgment PUBLISH - Publish message PUBACK - Publish Acknowledgment PUBREC - Publish Received (assured delivery part 1) PUBREL - Publish Release (assured delivery part 2) PUBCOMP - Publish Complete (assured delivery part 3) SUBSCRIBE - Client Subscribe request SUBACK - Subscribe Acknowledgment UNSUBSCRIBE - Client Unsubscribe request UNSUBACK - Unsubscribe Acknowledgment PINGREQ - PING Request PINGRESP - PING Response DISCONNECT - Client is Disconnecting Reserved - Reserved MQTT Spec v3.1 : http://www.ibm.com/developerworks/webservices/library/ws-mqtt/index.html http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/MQTT_V3.1_Protocol_Specific.pdf 13년 1월 28일 월요일
  • 13. Facebook 페이스북 엔지니어링 블로그 : http:/ /goo.gl/o1WGo 페이스북 메신저 앱 : http:/ /goo.gl/OfMer, http:/ /goo.gl/9RQhP NHN Helloworld Blog : http://helloworld.naver.com/helloworld/1846 13년 1월 28일 월요일
  • 15. Private Push Service POC * 서버 : RSMB, Mosquitto, etc... * 클라이언트 : Console, Web, Android Emul & Phone 13년 1월 28일 월요일
  • 16. MQTT Server - OpenSource * IBM RSMB (Really Small Message Broker) * Mosquitto (test.mosquitto.org) * IBM WebSphere MQ Telemetry * MQTT.js (Node.js) * eMQTT (Erlang) * RabbitMQ * Apache ActiveMQ * Apache Apollo * Moquette (Apache MINA) http://mqtt.org/software 13년 1월 28일 월요일
  • 17. MQTT Client - OpenSource * Device-specific * ActionScript * C / C++ * C# * Dephi * Erlang * Java * JavaScript / Node.js * .NET * Object-c * Perl * PHP * Python * REXX * Ruby http://mqtt.org/software 13년 1월 28일 월요일
  • 18. Private Push Server 선택 출처 : http://mqtt.org/wiki/doku.php/server_support 13년 1월 28일 월요일
  • 19. Mosquitto Sample 13년 1월 28일 월요일
  • 20. 솔루션을 만들어 팔 수 있을까? 13년 1월 28일 월요일
  • 21. Mosquitto - 1차 테스트 * Console & Mosquitto Command * Java Client Library OK ! * Mosquitto Java Client * Akka + IBM Paho Client * Python Client Libarry * python-mosquitto * MQTT-for-Twisted-Python * nyamuk Akka ( http://akka.io ) - Build powerful concurrent & distributed applications more easily. on the JVM 13년 1월 28일 월요일
  • 22. Mosquitto - 2차 성능 테스트 * 서버 1대 * CentOS 5.5 * Mosquitto 1 프로세스 6500 * 클라이언트 6500 * 맥북 프로 2대 + iMac 1대 * 각 6500개 Python Client * ipTime 공유기 n700 공유기 6500 mosquitto console broker 13년 1월 28일 월요일
  • 23. Mosquitto - 2차 결과 - 약 2만개 Python MQTT Client 안정적 접속 (2.5일간 유지) - CPU : 단일 코어 사용 - 메모리는 Client 수와 상관없이 일정하게 유지 - 연결 유지를 위한 Ping Req/Res의 트래픽 : 별도 전용선 - Publish Time 5초 ~ 6초 ( 이유는 ipTime 공유기의 한계 - 속도 지연) OK ! 13년 1월 28일 월요일
  • 24. 알게 된 것 1 : 별도의 전용 Line을 통한 서비스 알게 된 것 2 : Default FD <= 1024 13년 1월 28일 월요일
  • 25. import mosquitto def on_connect(mosq, obj, rc): print("rc: "+str(rc)) def on_message(mosq, obj, msg): print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload)) def on_publish(mosq, obj, mid): print("mid: "+str(mid)) def on_subscribe(mosq, obj, mid, granted_qos): print("Subscribed: "+str(mid)+" "+str(granted_qos)) def on_log(mosq, obj, level, string): print(string) # If you want to use a specific client id, use # mqttc = mosquitto.Mosquitto("client-id") # but note that the client id must be unique on the broker. Leaving the client # id parameter empty will generate a random id for you. mqttc = mosquitto.Mosquitto() mqttc.on_message = on_message mqttc.on_connect = on_connect mqttc.on_publish = on_publish mqttc.on_subscribe = on_subscribe # Uncomment to enable debug messages #mqttc.on_log = on_log mqttc.connect("test.mosquitto.org", 1883, 60) mqttc.subscribe("$SYS/#", 0) rc = 0 while rc == 0: rc = mqttc.loop() print("rc: "+str(rc)) https://bitbucket.org/oojah/mosquitto/src/tip/lib/python/sub.py 13년 1월 28일 월요일
  • 26. Default 1024 Error filedescriptor out of range in select() 13년 1월 28일 월요일
  • 27. Mosquitto Python MQTT Client select? mysql select? 13년 1월 28일 월요일
  • 28. Python IO * select - The first three arguments are sequences of ‘waitable objects’: either integers representing file descriptors * kqueue - kernel event notification mechanism * kevent - Returns a kernel event object * poll - better scalability for network servers that service many, many clients at the same time * epoll - Returns an edge polling object, which can be used as Edge or Level Triggered interface for I/O events 13년 1월 28일 월요일
  • 29. MQTT-For-Twisted-Python https://github.com/adamvr/MQTT-For-Twisted-Python/blob/master/MQTT.py MQTT4PythonTwistedDemo https://code.google.com/p/beaglebone-iot/wiki/MQTT4PythonTwistedDemo from twisted.internet import kqreactor kqreactor.install() .... if __name__ == '__main__': mqttMessageBuffer = [] clientCountRange = range(1, 1200) for r in clientCountRange: try: mqttFactory = MQTTListenerFactory() reactor.connectTCP("192.168.10.32", 1883, mqttFactory) except: log.msg("except " + sys.exec_info()) reactor.run() 13년 1월 28일 월요일
  • 30. What is Twisted? Twisted is an event-driven networking engine written in Python from twisted.internet import protocol, reactor class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFactory(protocol.Factory): def buildProtocol(self, addr): twisted.web import server, resource from return Echo() from twisted.internet import reactor class HelloResource(resource.Resource): reactor.listenTCP(1234, EchoFactory()) isLeaf = True reactor.run() numberRequests = 0 def render_GET(self, request): self.numberRequests += 1 request.setHeader("content-type", "text/plain") return "I am request #" + str(self.numberRequests) + "n" reactor.listenTCP(8080, server.Site(HelloResource())) reactor.run() 13년 1월 28일 월요일
  • 31. Twisted Document - Reactor Reactor Overview 1. Reactor Basics 2. Using the reactor object This HOWTO introduces the Twisted reactor, describes the basics of the reactor and links to the various reactor interfaces. Reactor Basics The reactor is the core of the event loop within Twisted -- the loop which drives applications using Twisted. The event loop is a programming construct that waits for and dispatches events or messages in a program. It works by calling some internal or external "event provider", which generally blocks until an event has arrived, and then calls the relevant event handler ("dispatches the event"). The reactor provides basic interfaces to a number of services, including network communications, threading, and event dispatching. Choosing a Reactor and GUI Toolkit Integration 1. Overview 2. Reactor Functionality 3. General Purpose Reactors ◦ Select()-based Reactor 4. Platform-Specific Reactors ◦ Poll-based Reactor ◦ KQueue ◦ WaitForMultipleObjects (WFMO) for Win32 ◦ Input/Output Completion Port (IOCP) for Win32 ◦ Epoll-based Reactor 5. GUI Integration Reactors ◦ GTK+ ◦ wxPython ◦ CoreFoundation 6. Non-Reactor GUI Integration ◦ Tkinter ◦ PyUI 13년 1월 28일 월요일
  • 32. Reactor Pattern? The reactor design pattern is an event handling pattern for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronously to the associated request handlers All reactor systems are single threaded by definition, but can exist in a multithreaded environment. C - libevent C++ - POCO C++ Libraries Java - Apache MINA, JBoss Netty, Apache Cocoon, Disruptor JavaScript - Node.js Perl - POE Python - Twisted Ruby - EventMachine http://en.wikipedia.org/wiki/Reactor_pattern 13년 1월 28일 월요일
  • 33. POSA 2 Patterns for Concurrent and Networked Objects 이미지 출처 : http://www.cs.wustl.edu/~schmidt/POSA/POSA2/ 13년 1월 28일 월요일
  • 34. Opps ! 이미지 출처 : http://goo.gl/HUiFZ 13년 1월 28일 월요일
  • 35. 만드는 이유? * 기업 => Push 마케팅 Tool * 기업 기간계 시스템 연동 : 보험, 증권, 은행, 쇼핑몰 => SMS/MMS = 비용 * 기업 자신들의 모바일 앱 고객 분석 13년 1월 28일 월요일
  • 36. 기업 개발 부서 반응 * 이런 걸 왜 사? * 내가 이틀이면 만들겠다 = 자체 개발? => 몇 달 뒤 전화 옴 * 발송만 보면 이틀이 아니라 몇 시간 내에 가능 => 맞는 말 * 그러나 기업 자체 개발 인력 부족, 자체 문제 및 요구사항 * History : 메일 = PUSH 13년 1월 28일 월요일
  • 37. 헉 !!! http://count.ly/ https://github.com/Countly node.js, mongodb, nginx https://github.com/isaacs/node-supervisor http:/ http:/ /countly.firejune.io/login /goo.gl/U63L1 supervisor, python 13년 1월 28일 월요일
  • 38. 정리 * Private Push Server 구축은 어렵지 않게 시작 할 수 있다. * 이를 구축하는데 MQTT 좋은 선택 * Python IO Server/Client => twisted 시작 * 국내 Push 독보적인 솔루션 없음 => 메일 시장 History 반복 13년 1월 28일 월요일
  • 39. 최종 보스 이미지 출처 : http://goo.gl/NF18A 13년 1월 28일 월요일
  • 41. * 참고 * 모바일 Push와 nPush - http:/ /helloworld.naver.com/helloworld/1119 * Android PUSH와 카카오톡 사건 - http:/ /mobizen.pe.kr/1074 * 3G에 대한 이해 - http:/ /helloworld.naver.com/helloworld/111111 * C500k - http:/ /www.mimul.com/pebble/default/2012/07/18/1342602654675.html * 어반 에어쉽 Architecture - http:/ /www.slideshare.net/eonnen/from-100s-to-100s-of-millions * MQTT * Test Server - http:/ /test.mosquitto.org/ * http://www.slideshare.net/andypiper/introducing-mqtt * ftp://public.dhe.ibm.com/software/kr/ik2012/mqtt.pdf * 활용 : http:/ /mqtt.org/wiki/doku.php/example_uses * http://stephendnicholas.com/archives/1217 * XMPP * Google App Engine - http:/ /goo.gl/lXHcM * Android Push - http:/ /blog.softwaregeeks.org/archives/530 * http://blog.doortts.com/148 * IBM 웹기반 알림 - http:/ /goo.gl/O8UEy * POSA 2 무료 강좌 - http:/ /www.devpia.com/NET2/EvaCast/Lecture/?fCode=1&sCode=2&c=4 13년 1월 28일 월요일