Originally published on Medium:
https://medium.com/@supsabhi/sockets-in-android-from-websockets-to-socket-io-with-jetpack-compose-example-5773828ba05b
Real-time updates are a real challenge! Every time we play games or use a chat application, the instant updates on screen always amaze us. How does the app receive updates without constantly refreshing APIs?
The answer is “Sockets.” Let’s dive deeper into sockets, explore different types, focus on IO sockets, and see how to implement them in Android Jetpack Compose.
A socket is like a live communication channel between your Android app and a server. Unlike standard HTTP APIs where you request data and wait for a reply, sockets remain connected and enable two-way communication. Think of it as a direct digital pipe — data can flow both ways, supporting fast, two-way updates without repetitive polling.
In practice, you can distinguish between HTTP and sockets like this:
HTTP: You send a request, the server replies, communication happens, and the process ends.
Sockets: Sockets can be viewed as ,suppose in the process of opening a phone call, you pick up phone and “keep the call alive” and both sides can talk anytime
There are different types of sockets, each used for specific purposes:
WebSockets: WebSocket is a W3C and IETF standardized protocol that offers a persistent channel over a single TCP connection. You can send or receive as much data as needed, without reopening new HTTP requests. It’s lightweight, efficient, and ideal for streaming data. WebSockets are commonly used in live sports updates, stock prices, collaborative docs, and IoT device status — where low latency and immediate updates are essential.
Socket.IO: Socket.IO isn’t a protocol, but a full-featured library built on top of WebSockets (with fallbacks). It manages fallbacks, reconnections, broadcasting, event naming, and more. It’s easier for developers because it solves real-world connection issues out of the box. Socket.IO is mainly used for chat apps, live games, and push notification dashboards.
Raw TCP/UDP Sockets: These are low-level protocols. TCP enables reliable raw byte transfer and is used in file transfer and messaging. UDP is faster but less reliable than TCP and is used in video streaming and gaming. Raw TCP/UDP sockets offer custom device-to-device control and binary protocol capabilities.
Let’s focus more on our star: Socket.IO.
Socket.IO smooths over many networking headaches, especially for mobile: reconnection logic, event-centric APIs, message buffering during downtimes, and support for various network topologies. It certainly deserves special recognition.
Implementation in Android Jetpack Compose
Below is an example of live updating a dashboard based on the server’s latest information.
(First, add implementation
'io.socket:socket.io-client:2.1.0'
to your build.gradle.)
Make sure the socket client version matches the server version.
Also, add the internet usage permission in your manifest.
Data Model Class
data class DashBoardMessage(val var1: String, val var2: String, val var3: String)
ViewModel
class DashBoardViewModel : ViewModel() {
var latestMessage by mutableStateOf<DashBoardMessage?>(null)
private set
private val socketManager = SocketManager()
fun start() {
socketManager.connect { message ->
latestMessage = message
}
}
override fun onCleared() {
super.onCleared()
socketManager.disconnect()
}
}
Socket Manager
class SocketManager {
private var socket: Socket? = null
fun connect(onMessage: (DashBoardMessage) -> Unit) {
try {
val opts = IO.Options().apply { forceNew = true }
socket = IO.socket("https://your-socket-server.com", opts)
socket?.on(Socket.EVENT_CONNECT) {
Log.d("SocketIO", "Connected")
}
socket?.on("message") { args ->
if (args.isNotEmpty() && args[0] is JSONObject) {
val json = args[0] as JSONObject
val msg = DashBoardMessage(
var1 = json.optString("var1"),
var2 = json.optString("var2"),
var3 = json.optString("var3")
)
Handler(Looper.getMainLooper()).post {
onMessage(msg)
}
}
}
socket?.connect()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun disconnect() {
socket?.disconnect()
socket?.off()
}
}
Compose Screen
@Composable
fun DashboardScreen(viewModel: DashBoardViewModel = viewModel()) {
val msg = viewModel.latestMessage
LaunchedEffect(Unit) {
viewModel.start()
}
Column(modifier = Modifier.padding(16.dp)) {
Text("Var1: ${msg?.var1 ?: ""}")
Text("Var2: ${msg?.var2 ?: ""}")
Text("Var3: ${msg?.var3 ?: ""}")
}
}
With this setup, you get real-time, event-driven updates in a Compose UI. Incoming messages instantly update the screen, and sending a message emits it to the server — no need for manual thread handling or traditional callbacks.
Sockets might sound technical, but with tools like Socket.IO, creating a real-time, mobile-friendly Android app becomes straightforward.
So next time you need live updates — whether for a parking system, chat app, or stock ticker — reach for sockets instead of hammering your APIs.
GitHub Repository for Hands-On Reference
To make this article more practical and hands-on, I’ve published a public GitHub repository that demonstrates everything discussed above.
📂 GitHub Repository:
https://github.com/supsabhi/IoSocketJetPack.git
Top comments (0)