What are sockets?
Socket is a combination of an IP address and a port number
Socket example: 192.168.0.1:80
Sockets have two types:
Datagram sockets
● Use UDP for data transmission.
● Not 100% reliable and may lose data.
● Data sent/received order might not be the same
● Don't care or rapid recovering lost/mistaken data
Stream sockets
● Use TCP protocol for data transmission.
● Reliable and Lossless.
● Data sent/received in the similar order.
● Long time for recovering lost/mistaken
data
Socket usage in Android: Push notifications
WebSockets
Communication protocol providing full-duplex communication
channels over a single TCP connection.
The WebSocket protocol enables interaction between a client
and a web server with lower overheads, facilitating real-time
data transfer from and to the server.
The communications are done over TCP port number 80 (or 443
in the case of TLS-encrypted connections)
The WebSocket Protocol has two parts: a handshake to
establish the upgraded connection, then the actual data transfer.
Client handshake
Server response
What is Socket.io?
Socket.io is a library ported from javascript to java for real-time applications.
It enables real-time, bi-directional communication between clients and servers.
It has two parts: client-side library which used in Android and server-side library
for Node.js.
Example of real-time applications: chats, trading apps.
Getting started
Add dependency
implementation(“io.socket:socket.io-client:$socketIoVersion”) {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
Add internet permission into manifest
<uses-permission android:name="android.permission.INTERNET" />
Create service which handle sockets and declare it into manifest
<manifest
...
<application
…
<service
android:name=".network.service.SocketService"
android:exported="false" />
...
</application>
</manifest>
Preparing socket.io client
IO.Options
Options class represents object with default parameters for socket client
forceNew - is need to create new connection each time.
reconnection - is reconnection allowed.
reconnectionAttempts - reconnection attempts number.
reconnectionDelay - delay before each reconnection attempt.
reconnectionDelayMax - maximum delay before each reconnection attempt.
transports - List of transport names.
hostname - host name.
secure - is connection secured
port - port of sockets, if secured connection default port = 443 else 80
Options creation example
val options = IO.Options()
with(options) {
forceNew = true
secure = true
transports = arrayOf("websocket")
reconnectionDelay = 2000L
reconnectionDelayMax = 5000L
}
Initializing of socket client
Socket client have 2 parameters for initialization url (URI or String) and optional
parameter Options with socket parameters
var socket: Socket? = IO.socket(url, options)
?: IO.socket(uri, options)
?: IO.socket(url)
?: IO.socket(uri)
Connecting/Disconnecting
Usually called in onCreate() method of service
socket.connect()
Usually called in onDestroy() method of service
socket.disconnect()
Socket events
Start event listening
socket.on(“Event name”, Emitter.Listener listener)
Emitter.Listener - interface where we receive response from our events. In this
listener we receive vararg arguments:Any
// example of event
socket.on(“some event name”, { /*do something with received data*/ })
One time listener
If there was an event which we need to listen only once and then unsubscribe
from it we can to use socket.once(“Event name”, Emitter.Listener listener)
// example of event
socket.once(“some event name”, { /*do something with received data*/ })
After event received we unsubscribe from this event automatically.
Stop listening event
socket.off(“Event name”, Emitter.Listener listener)
or
socket.off(“Event name”) to remove all listeners of the specified event.
or
socket.off() to remove all registered listeners
Send an event
socket.emit(“Event name”, vararg arguments: Any)
vararg arguments: Any - arguments to emitting event, it most of cases this will be
json
socket.emit(“some event name”, “{“id”:1, “name”: “Some name”}”)
Default events
Socket.io already have default listened events
EVENT_OPEN = “open” - fired when socket open
EVENT_PACKET = “packet” - fired when packet received. Packet object represents any received event
such as “connect”, “disconnect”,”event” etc.
EVENT_CLOSE = “close” - fired when socket closed
Heartbeat events
Heartbeat protocol generally used to negotiate and monitor the availability of a
resource
socket.on(Socket.EVENT_PING, { }) Fired when a ping packet is written out to the server.
socket.on(Socket.EVENT_PONG, { /* here we receive latency */ }) Fired when a pong is received from the
server. Also we receive latency.
Under the box
Socket.io works under the okhttp3 WebSocket client for websocket transport
and HttpUrlConnection for polling transport
When socket connection opened socket.io emmits handshake event with received
handshake data from server which sets ping interval and ping timeout for
heartbeat event.
All tasks run with EventThread class which handles all socket.io events
Stored events
All event listeners stored in ConcurrentMap<String, ConcurrentLinkedQueue<Listener>>
All this listeners can be received by method socket.listeners(String event) which
return list of listeners which subscribed to event.
Best practice
● Create service for handle socket connection, with this way you can create
socket connection only once and use it in your whole app
● Close socket connection when you don’t need them, it reduce battery usage
● Unsubscribe from unnecessary events
● Use “once” listener for events which need to handle only once, this event will
be unsubscribed automatically
Socket.io v.0.8.3

Socket.io v.0.8.3

  • 2.
    What are sockets? Socketis a combination of an IP address and a port number Socket example: 192.168.0.1:80 Sockets have two types: Datagram sockets ● Use UDP for data transmission. ● Not 100% reliable and may lose data. ● Data sent/received order might not be the same ● Don't care or rapid recovering lost/mistaken data Stream sockets ● Use TCP protocol for data transmission. ● Reliable and Lossless. ● Data sent/received in the similar order. ● Long time for recovering lost/mistaken data Socket usage in Android: Push notifications
  • 3.
    WebSockets Communication protocol providingfull-duplex communication channels over a single TCP connection. The WebSocket protocol enables interaction between a client and a web server with lower overheads, facilitating real-time data transfer from and to the server. The communications are done over TCP port number 80 (or 443 in the case of TLS-encrypted connections) The WebSocket Protocol has two parts: a handshake to establish the upgraded connection, then the actual data transfer. Client handshake Server response
  • 4.
    What is Socket.io? Socket.iois a library ported from javascript to java for real-time applications. It enables real-time, bi-directional communication between clients and servers. It has two parts: client-side library which used in Android and server-side library for Node.js. Example of real-time applications: chats, trading apps.
  • 5.
  • 6.
    Add dependency implementation(“io.socket:socket.io-client:$socketIoVersion”) { //excluding org.json which is provided by Android exclude group: 'org.json', module: 'json' }
  • 7.
    Add internet permissioninto manifest <uses-permission android:name="android.permission.INTERNET" />
  • 8.
    Create service whichhandle sockets and declare it into manifest <manifest ... <application … <service android:name=".network.service.SocketService" android:exported="false" /> ... </application> </manifest>
  • 9.
  • 10.
    IO.Options Options class representsobject with default parameters for socket client forceNew - is need to create new connection each time. reconnection - is reconnection allowed. reconnectionAttempts - reconnection attempts number. reconnectionDelay - delay before each reconnection attempt. reconnectionDelayMax - maximum delay before each reconnection attempt. transports - List of transport names. hostname - host name. secure - is connection secured port - port of sockets, if secured connection default port = 443 else 80
  • 11.
    Options creation example valoptions = IO.Options() with(options) { forceNew = true secure = true transports = arrayOf("websocket") reconnectionDelay = 2000L reconnectionDelayMax = 5000L }
  • 12.
    Initializing of socketclient Socket client have 2 parameters for initialization url (URI or String) and optional parameter Options with socket parameters var socket: Socket? = IO.socket(url, options) ?: IO.socket(uri, options) ?: IO.socket(url) ?: IO.socket(uri)
  • 13.
    Connecting/Disconnecting Usually called inonCreate() method of service socket.connect() Usually called in onDestroy() method of service socket.disconnect()
  • 14.
  • 15.
    Start event listening socket.on(“Eventname”, Emitter.Listener listener) Emitter.Listener - interface where we receive response from our events. In this listener we receive vararg arguments:Any // example of event socket.on(“some event name”, { /*do something with received data*/ })
  • 16.
    One time listener Ifthere was an event which we need to listen only once and then unsubscribe from it we can to use socket.once(“Event name”, Emitter.Listener listener) // example of event socket.once(“some event name”, { /*do something with received data*/ }) After event received we unsubscribe from this event automatically.
  • 17.
    Stop listening event socket.off(“Eventname”, Emitter.Listener listener) or socket.off(“Event name”) to remove all listeners of the specified event. or socket.off() to remove all registered listeners
  • 18.
    Send an event socket.emit(“Eventname”, vararg arguments: Any) vararg arguments: Any - arguments to emitting event, it most of cases this will be json socket.emit(“some event name”, “{“id”:1, “name”: “Some name”}”)
  • 19.
    Default events Socket.io alreadyhave default listened events EVENT_OPEN = “open” - fired when socket open EVENT_PACKET = “packet” - fired when packet received. Packet object represents any received event such as “connect”, “disconnect”,”event” etc. EVENT_CLOSE = “close” - fired when socket closed
  • 20.
    Heartbeat events Heartbeat protocolgenerally used to negotiate and monitor the availability of a resource socket.on(Socket.EVENT_PING, { }) Fired when a ping packet is written out to the server. socket.on(Socket.EVENT_PONG, { /* here we receive latency */ }) Fired when a pong is received from the server. Also we receive latency.
  • 21.
    Under the box Socket.ioworks under the okhttp3 WebSocket client for websocket transport and HttpUrlConnection for polling transport When socket connection opened socket.io emmits handshake event with received handshake data from server which sets ping interval and ping timeout for heartbeat event. All tasks run with EventThread class which handles all socket.io events
  • 22.
    Stored events All eventlisteners stored in ConcurrentMap<String, ConcurrentLinkedQueue<Listener>> All this listeners can be received by method socket.listeners(String event) which return list of listeners which subscribed to event.
  • 23.
    Best practice ● Createservice for handle socket connection, with this way you can create socket connection only once and use it in your whole app ● Close socket connection when you don’t need them, it reduce battery usage ● Unsubscribe from unnecessary events ● Use “once” listener for events which need to handle only once, this event will be unsubscribed automatically

Editor's Notes

  • #3 Сокет - это абстрактный объект представляющий собой эндпоинт, который является комбинацией IP-адреса и номера порта. Сокеты делятся на 2 типа: Стрим сокеты и датаграм сокеты. Стрим сокеты - используют TCP протокол для передачи данных, могут поддерживать безопасное соединение и работают без потерь данных. Данные принимаются и отправляются сохраняя порядок.Значительные затраты времени для восстановления потерянных либо ошибочных данных. Датаграм сокеты - используют UDP для передачи данных, не 100% безопасны и могут терять данные. Отправленные/ полученные данные могут не соблюдать порядок. Не восстанавливают либо быстро восстанавливают потерянные/ ошибочные данные. Датаграм сокеты обычно используются в геймдеве и VoIP где соблюдение порядка пакетов не так важно. Стрим сокеты используются в случае когда порядок и сохранность полученных/отправленных пакетов важна, например передача файлов.
  • #4 WebSockets - это протокол связи обеспечивающий двустороннюю связь между каналами через единое TCP соединение. Веб сокеты обеспечивают взаимодействие между клиентом и сервером при более низкий нагрузках, облегчая передачу данных в реальном времени. Связь по веб сокетам проходит через TCP 80 или 443 порт в случае если соединение защищено TLS-шифрованием. Для установки TCP соединения клиент отправляет на сервер хендшейк с HTTP Upgrade хедером для изменения HTTP протокола на WebSocket протокол, и в случае если сервер поддерживает протокол, он отвечает теми же хедерами и завершает хендшейк. Как только хендшейк завершен успешно начинается передача данных.
  • #5 Socket.io это библиотека портированная из javascript на java для риал-тайм приложений. Она обеспечивает двунаправленное соединение в реальном времени между клиентом и сервером. Состоит из 2х частей: клиентской библиотеки, которая используется на андроиде и серверной библиотеки для Node.js Применяется в приложениях в которых есть чаты, в трейдинговых приложениях и тд.
  • #13 Для инициализации сокет клиента нам предоставляют 4 метода, в которых обязательным параметром является ендпоинт сокета и опциональный параметр Options.