Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Kristaps Grinbergs
Kristaps Grinbergs

Posted on

     

Clearing up after subscribing to Swift WebSockets

Opening and keeping a WebSocket connection alive isn't enough when dealing with it. The connection needs to be closed either from user or sever side. That ismentioned in the official WebSocket protocol.

Previously we have seen how to implement WebSockets usingStarscream library,URLSessionWebSocketTask andGraphQL in Swift projects. This time we will look into cleaning up the connection after you don’t need it anymore.

If you leave the connection open and don’t clean up properly various problems can arise: memory leaks, server overworking and data corruptions.

Closing the WebSocket

As we are looking at how to close connection from user agent there are couple of things to consider. When closing the connection we need to inform server about the reason using "close" code which can be useful for server developers. There are several "close" codes which you can check out inRFC 6455 specification or simplified versionhere.

If anything goes wrong with the connection on user side connection should be closed. It is important to note that when user agent notices that server has closed its connection, it should do the same on the other side. That means you need to explicitly inform the server about such event (regardless of the closure on the user side). That is clearlystated in the official WebSocket protocol.

Cancel the URLSessionWebSocketTask

To cancel aURLSessionWebSocketTask you need to call acancelmethod.

When calling this instance method you need to provide aclose code and a reason.

leturl=URL(string:"wss://echo.websocket.org")!letwebSocketTask=URLSession.shared.webSocketTask(with:url)// ...webSocketTask.cancel(with:.goingAway,reason:nil)
Enter fullscreen modeExit fullscreen mode

Disconnect with Starscream

To close a WebSocket created with libraryStarscream you need to call adisconnect method. If you want to specify it in the close code you can do so, but it is optional.

letsocket=WebSocket(url:URL(string:"ws://localhost:8080/")!)// ...socket.disconnect(closeCode:CloseCode.normal.rawValue)
Enter fullscreen modeExit fullscreen mode

Cancel subscriptions with GraphQL

When using GraphQL with subscriptions Apollo protocol handles all the heavy duty work behind the scenes. Clients can get immediate data changes from the server.

In Apollo iOS SDK library subscriptions areCancellableprotocol types. It is an object that can be cancelled when in progress and it has just one methodcancel.

In order to clean up after GraphQL subscriptions are not needed anymore the easiest way is to keep track of all subscriptions and cancel when needed or do the cleanup within objectdeinit method.

varsubscriptions:[Cancellable]// ...letnewPricesSubcriprion=ApolloClient.subscribe(NewPricesSubscription()){...}// ...subscriptions.forEach{subscriptioninsubscription.cancel()}
Enter fullscreen modeExit fullscreen mode

TL;DR

When working with WebSockets we need to remember to close connections and clean up. Forgetting to do so we can run into multiple issues which can later be hard to debug and understand.

We can use WebSockets in our Swift projects in multiple ways and each one requires a different approach to close the connection. But most importantly as WebSocket protocol tells us we need to do it either connection is closed from the user or server side.

Links

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Mobile and fullstack developer. Startup founder. Conference speaker. Mentor. Passionate about building products, sustainability and Web 3.0.
  • Location
    Latvia
  • Education
    CS Master
  • Joined

More fromKristaps Grinbergs

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp