WebSocket Connection for Mobile App Chat

NOVASOLUTIONS.TECHNOLOGY is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.
Development and support of all types of mobile applications:
Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1 servicesAll 1735 services
WebSocket Connection for Mobile App Chat
Medium
~3-5 business days
FAQ
Our competencies:
Development stages
Latest works
  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    756
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    624
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1054
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    947
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    862
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    445

WebSocket Connection Integration for Mobile Chat

WebSocket gives full-duplex connection with minimal overhead compared to polling — correct choice for real chat. But mobile specifics add complexity layer: app goes to background, network switches from Wi-Fi to LTE, user locks screen. WebSocket client working well on desktop can lose connection in 30 seconds after background on iOS due to aggressive resource management.

Connection Management — Main Complexity

iOS. Background execution for WebSocket officially unsupported. If app needs receiving messages in background — only official path is push notifications (APNs). WebSocket stays active only while app in foreground. Attempts to keep connection alive via URLSessionWebSocketTask with background URLSessionConfiguration work unstably and violate Guidelines.

On iOS use URLSessionWebSocketTask (iOS 13+):

class WebSocketManager {
    private var webSocketTask: URLSessionWebSocketTask?

    func connect() {
        let session = URLSession(configuration: .default, delegate: self, delegateQueue: .main)
        webSocketTask = session.webSocketTask(with: URL(string: "wss://api.example.com/ws")!)
        webSocketTask?.resume()
        receiveMessage()
    }

    private func receiveMessage() {
        webSocketTask?.receive { [weak self] result in
            switch result {
            case .success(let message):
                self?.handleMessage(message)
                self?.receiveMessage() // recursively
            case .failure(let error):
                self?.scheduleReconnect()
            }
        }
    }
}

Android. OkHttp WebSocket — de facto standard. In background connection can be cut by JobScheduler or Doze Mode on Android 6+. Solution: WorkManager for periodic sync + FCM push for background message delivery. Keep WebSocket alive only when app in foreground, optionally — ForegroundService with notification.

val client = OkHttpClient.Builder()
    .pingInterval(30, TimeUnit.SECONDS) // heartbeat
    .build()

val request = Request.Builder().url("wss://api.example.com/ws").build()
val ws = client.newWebSocket(request, object : WebSocketListener() {
    override fun onMessage(webSocket: WebSocket, text: String) {
        // handle message
    }
    override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
        scheduleReconnect()
    }
})

pingInterval(30) important — without heartbeat connection breaks by intermediate proxies after 60–90 seconds silence.

Reconnection with Exponential Backoff

Reconnection on break — mandatory logic. Simple retry via 1 second creates request storm on server fall. Correct approach — exponential backoff with jitter:

private var reconnectDelay = 1000L

fun scheduleReconnect() {
    viewModelScope.launch {
        delay(reconnectDelay + Random.nextLong(500))
        reconnectDelay = minOf(reconnectDelay * 2, 30_000L)
        connect()
    }
}

fun onConnected() {
    reconnectDelay = 1000L
}

Flutter: web_socket_channel package — wrapper over native implementations. For production level recommend stomp_dart_client if server uses STOMP, or custom manager with same reconnect principles.

Authentication

WebSocket connection authenticated once on establishment — via Authorization header in handshake or first message after connect (auth frame). JWT token may expire during session — need token refresh and reconnection logic.

What's Included

Implement WebSocket client per platform with reconnect logic, heartbeat, network change handling (NetworkCallback on Android, NWPathMonitor on iOS). If fallback to push needed — integrate APNs/FCM for background message delivery.

Timeline: 4–8 days for full implementation considering network edge-cases.