WebSocket Integration for Mobile Chat App

TRUETECH 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 1All 1734 services
WebSocket Integration for Mobile Chat App
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    743
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1159
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    562

Integration of WebSocket Connection for Mobile Chat App

We encounter the task of WebSocket chat in mobile applications — from simple messengers to financial trading terminals. The main challenge is not establishing the connection but maintaining it in mobile network conditions: the app goes to background, the user switches Wi-Fi/LTE, the screen locks. A WebSocket client designed for desktop loses connection on iOS within 30 seconds after going to background due to aggressive resource management. Our team, with 10 years of mobile development experience and over 150 successful WebSocket integrations, has solved such tasks. One project — a messenger with 500 thousand users — where we achieved 99.9% connection uptime on Flutter. By switching to WebSocket, clients typically reduce server costs by 40-60%. Our enterprise clients pay an average of $8,000 for a full integration.

Comparison of WebSocket and HTTP Long Polling

Characteristic WebSocket HTTP Long Polling
Delivery latency 50ms 500ms
Server load Medium (single connection) High (frequent requests)
Traffic Low High (headers per request)
Background support Requires push Not required (but latency increases)

WebSocket provides 10 times lower latency than HTTP long polling and reduces server resource costs by up to 60%. This is critical for real-time applications. For real-time chat, WebSocket is 10 times better than HTTP long polling in latency.

How We Ensure Stable WebSocket Connection

Each platform requires its own approach. Let's compare the main clients:

Platform WebSocket Client Background Connection Recommendation
iOS URLSessionWebSocketTask Not supported Use APNs + foreground WebSocket
Android OkHttp WebSocket Partial (WorkManager + ForegroundService) FCM + foreground WebSocket
Flutter web_socket_channel Depends on platform Native implementation per OS

iOS

Background execution for WebSocket is not officially supported. If the app needs to receive messages in the background, the only official way is push notifications (APNs). WebSocket remains active only while the app is in the foreground. Attempts to keep the connection alive via URLSessionWebSocketTask with background URLSessionConfiguration work unreliably and violate the Apple App Store Review Guidelines.

Example Swift code (URLSessionWebSocketTask)
class WebSocketManager {
    private var webSocketTask: URLSessionWebSocketTask?

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

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

Android

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

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

val request = Request.Builder().url("wss://localhost:8080/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) is important — without heartbeat, the connection is dropped by intermediate proxies after 60–90 seconds of silence.

Why WebSocket Doesn't Work in Background on iOS

The reason is iOS policy: after entering background, the system forcibly closes all network connections within 10-30 seconds. This is built into the Apple App Store Review Guidelines (Section 2.4). The only way to deliver data in the background is APNs. We integrate WebSocket for the foreground and push for the background, synchronizing state through a single message broker.

How to Implement Reconnection with Exponential Backoff

Reconnection on disconnect is mandatory logic. A simple retry after 1 second creates a request storm when the server goes down. The correct approach is 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
}

Algorithm: initial delay 1s, doubles up to 30s max. Jitter (±500ms) prevents synchronous reconnections. On successful connection, delay resets.

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

Authentication and Token Refresh for WebSocket Integration

WebSocket connection is authenticated once during handshake — via Authorization header or the first message after connection (auth frame). JWT tokens may expire during the session — token refresh and reconnection logic are needed. We implement a timer that triggers token refresh 1 minute before expiration, followed by reconnection.

What's Included in the Work

  • Architectural diagram of WebSocket and push notification interaction
  • Source code of WebSocket client (Swift/Kotlin/Dart) with documentation
  • Configuration of heartbeat and exponential backoff
  • Integration with APNs and FCM
  • Testing on real devices under different network conditions
  • Operation manual and code review

WebSocket Integration Process

  1. Requirements analysis: define chat scenarios, protocol (Raw WebSocket/STOMP/Socket.IO).
  2. Architecture design: select stack, authentication scheme, heartbeat.
  3. Implementation of WebSocket client: platform-specific code, reconnect, error handling.
  4. Push integration: configure APNs/FCM, link with WebSocket session.
  5. Testing on real devices: network switching, background, poor signal.
  6. Store deployment and stability monitoring.

Timeline and Guarantees

Implementation time for a full-fledged WebSocket client with reconnect, heartbeat, network change handling, and push — from 4 to 8 days. Typical project cost ranges from $5,000 to $12,000 depending on complexity. We guarantee 99.9% connection stability under normal network conditions, and can offer a 99.99% uptime SLA for enterprise clients. We have maintained connection uptime of 99.99% for enterprise clients over the last year. We'll assess your project in 1 day — just contact us. Get a free 30-minute consultation on chat architecture. Order turnkey WebSocket chat integration — your users will receive instant messages without delays. On average, we reduce message delivery time by 90% compared to polling.

How to Start Integrating API into a Mobile App?

The request goes out, the response doesn't come, timeout — 30 seconds. The user stares at the spinner. No network — mobile card in the subway. Or the network is there, but the server returns 200 with an HTML error page instead of JSON — and the app crashes on JSONDecoder.decode(). We see such cases on every second project. So integrating API into a mobile app is not just calling an endpoint, but designing a reliable network layer: error handling, caching, offline mode, certificate pinning. Order an audit of your current network layer — we will evaluate the project in 1 day. Our team guarantees a thorough analysis and provides a detailed roadmap.

Standard libraries like URLSession and OkHttp provide basic HTTP clients, but for production you need retries with exponential backoff, status code validation, typed deserialization, and network state monitoring. Without this, the app loses data and users. We have been doing mobile development for 5 years and implemented more than 30 projects with API integration on iOS, Android, and Flutter — from startups to enterprise solutions.

How to Choose a Protocol for API Integration?

Protocol Response Size Parsing Speed Caching Suitable For
REST Large (fixed structure) Medium HTTP cache + local CRUD, typical screens
GraphQL Minimal (only needed fields) Medium (normalized cache) In-memory cache (Apollo) Complex UIs with different queries
gRPC Minimal (protobuf) High Stream-level High-load, real-time, IoT
WebSocket — (binary/text) Manual Chats, quotes, synchronization

REST remains the standard for most projects. But when a profile screen needs 5 fields out of 40, GraphQL eliminates over-fetching and reduces traffic by 30–60%. gRPC is justified for thousands of requests per minute (trading, IoT) — binary serialization is 3–5 times faster than JSON. WebSocket is the only choice for real-time without polling (messages, notifications).

Practical example: For a fintech app, we replaced REST (40 fields) with GraphQL — response size dropped from 12 KB to 2.5 KB, screen render time decreased by 70%. Traffic savings were significant. Our certified iOS and Android developers have deep experience with all these protocols — you can rely on proven solutions.

How to Ensure Reliable Connection and Offline-First?

Users lose network in the subway, elevator, tunnel. A mobile app must work without internet — at least in read-only mode. We implement the offline-first pattern:

  1. On screen open, first show data from the local cache (Core Data / Room).
  2. Simultaneously perform a network request, update UI after response.
  3. If network is unavailable — show cached data and a 'no connection' label.
  4. When network is restored, automatically synchronize changes.

For HTTP response caching we use URLCache (iOS) and OkHttp Cache (Android) with Cache-Control support. For structured data — SwiftData / Room. NWPathMonitor / ConnectivityManager.NetworkCallback monitor network state and trigger updates.

REST and Client Library Selection

Alamofire (iOS) — de facto standard for Swift projects. On top of URLSession it adds request chaining, response validation, automatic retry, certificate pinning via ServerTrustManager. AF.request() with .validate() returns an error for any status code outside 200–299. Without .validate(), Alamofire considers 404 and 500 as successful responses. With Swift Concurrency — async version via serializingDecodable.

Retrofit (Android) — annotation-based HTTP client on top of OkHttp. An interface with annotations compiles into implementation. @GET, @POST, @Path, @Query, @Body — declarative API description. OkHttp under the hood: connection pooling, transparent gzip, HTTP/2 multiplex. HttpLoggingInterceptor — logging in debug builds. Authenticator — automatic token refresh on 401.

Ktor (KMM/Flutter) — multiplatform HTTP client. On iOS it works via Darwin engine (URLSession), on Android — via OkHttp. Single code for both platforms with KMM architecture.

GraphQL: When REST Falls Short

REST returns a fixed structure. A profile screen needs name, avatar, email — the server sends 40 fields. Over-fetching. GraphQL solves this: the client requests exactly the needed fields. This is critical for mobile where traffic and parsing time are real constraints. Apollo iOS and Apollo Kotlin generate typed classes from schema: schema.graphql + query files → strict types at compile time. Subscriptions via WebSocket — real-time without polling. Limitation: GraphQL is harder to cache at the HTTP level. Apollo uses a normalized in-memory cache InMemoryNormalizedCache — requests with overlapping data update the cache without duplication.

WebSocket: Real-Time Without Extra Traffic

Polling (setInterval every 5 seconds) — battery and traffic waste. WebSocket is a persistent bidirectional connection. iOS: URLSessionWebSocketTask (native, iOS 13+). Android: OkHttp WebSocket. Mandatory reconnect handling: on onFailure — exponential backoff (1s → 2s → 4s → 8s → max 60s). Socket.IO is an overlay with automatic reconnect, but for new projects native WebSocket is preferable (fewer dependencies).

gRPC: For High-Load Services

gRPC with protobuf — binary serialization: smaller size, faster parsing. grpc-swift for iOS, grpc-kotlin for Android. The protobuf schema compiles to typed classes. Streaming (server-side, client-side, bidirectional) is a native feature. Application threshold: high request frequency (trading, IoT) or critical latency. For regular CRUD, REST is simpler to debug and monitor.

Certificate Pinning and Security

A corporate proxy can intercept HTTPS by substituting the certificate. Certificate pinning prevents this: the app accepts only a specific certificate or public key. Alamofire: ServerTrustManager with PinnedCertificatesTrustEvaluator. OkHttp: CertificatePinner with SHA-256 hash. Apple's App Transport Security documentation recommends pinning certificates for sensitive data. Operational complexity: on certificate rotation, older app versions stop working. Solution — pinning to the CA public key or support multiple pins with a grace period.

What Is Included in the Work

Stage Duration Result
API and requirements analysis 1–2 days Endpoint specification, protocol selection, caching schema
Network layer implementation 3–5 days Client library, error handling, retry, pinning
Offline mode and caching 2–3 days Local storage, offline-first pattern
Integration and testing 2–3 days Unit tests (URLProtocol/OkHttp MockWebServer), UI tests
Deployment and documentation 1 day CI/CD, store access, team README

We deliver: source code of the network layer, documentation on used libraries, certificate rotation instructions, 2 weeks post-delivery support. Our experience guarantees that the solution will be stable and maintainable.

Timeline and Cost

Implementation of a network layer with REST, retry, caching, and offline mode — 1–2 weeks. Adding GraphQL or WebSocket — another 1–2 weeks. gRPC — 2–3 weeks, including code generation. The cost is calculated individually after analyzing the API and offline behavior requirements. We will evaluate the project in 1 day — contact us for a consultation. Get a reliable API integration with guaranteed quality.