Swift — WebSockets (Socket Rocket)
While surfing through job interviews I was requested to build an app that uses WebSocket, It was a home test, they gave me 90 minutes, the WebSocket returned an object with text fields (Key-Value) inside (nothing fancy), I was asked to get the message, parse it and present it on screen in a collection view, pretty simple right?
I didn't have much experience with WebSocket until then, so the first thing I went to research is, what is a WebSocket?
What is WebSocket?
A WebSocket is a communication protocol, the protocol provides a full-duplex communication (both sides can send and receive data), the protocol runs over TCP (Transmission Control Protocol).
The advantage of WebSocket over half-duplex HTTP polling is that it gives relatively low overhead, this is possible because the client and server hold an open “pipe” between them that allows both to transfer data without requesting to open a connection first.
So, after I shortly researched what a WebSocket is, I went ahead and looked for an implementation I can use in the iOS app I was requested to build.
A Google search came up with few results, the one I decided to use was Socket Rocket.
Why Socket Rocket? Firstly it was developed by Facebook, a big company like that made me think the package will be maintained and will provide me with everything I need for my task, also the amounts of stars on their git repository (9.2k) made me think that it was vastly used.
Socket Rocket
With every package you want to use in your app, the first step was integrating it into your app, two possible ways to do it with Socket Rocket
1. CocoaPods — pod ‘SocketRocket
and then you need to run pod install
.
2. Carthage — github "facebook/SocketRocket"
add the following to your Cartfile and run carthage update
.
After we integrated the package into our code, we can start using it to get (and send data if we like) to our WebSocket.
Let’s get to work, I usually open a new helper class so I can have all the WebSocket logic in one place.
In my helper class I need to import the Socket Rocket package but entering the following line:import SocketRocket
Initialize Socket Rocket
We need to initialize the Socket Rocket object:
The following code demonstrates how to initialize the Socket Rocket object SRWebSocket
. Code explanation:
1. We first turn our url string into a URL
object.
2. Define a new URLRequest
object and put the url into it
3. Create a new SRWebSocket
object and give it the URLRequest
.
4. Put the helper class as delegate
for the socket (we’ll see soon why).
5. open the socket using the open()
function.
Once we’re done with the initialization, we have an open connection (pipe) between our app and the server.
SRWebSocketDelegate
Next step, we want to receive messages, how can we do that?
For that exact purpose, we just set our helper class as delegate
for the SRWebSocket
object we created.
Socket Rocket package gives us SRWebSocketDelegate
, the delegate gives us a few useful functions we can use.
Let’s look at some of them:
webSocketDidOpen
— called when the WebSocket is opened successfully.didFailWithError
— called when the WebSocket fails to open, gives us the Error
object and the reason for failing.didCloseWithCode
— called when the WebSocket is closed with the code, which indicates why the WebSocket was closed.didReceiveMessage
— called when the WebSocket receives a message.
Important: the message can be anything, that’s why the object is Any!
.
We don’t have to implement all of those delegate functions, it depends on the app's needs.
Recieve a message
The function we do want to look at is didReceiveMessage
, this function allows us to get the message from the server-side and do whatever we want with it, as I mentioned before, as part of my home test I was requested to parse the message and present it in a collection view. messages were sent constantly at the rate of one message per second.
Once the server send a message over the following code will be executed:
The following code snippet handles the message from the server, we first make sure that the message does exist using the guard
code word (if you are not sure what guard
is you check my article about it here), you then can do whatever is needed with the message.
Close the socket
Once we’re finished with the socket, or the app closes we need to let the server know that we longer require this pipe to be open, we need to close the SRWebSocket
object:
The following snippet checks if the SRWebSocket does exist, and if it does it calls the close()
function to close the “pipe” between the server and the app, it terminated the connection between the server and client and no data can be exchanged unless we open the WebSocket again.
Conclusion
WebSockets are a great way to have full-duplex communication with your server, one of the needs I can think of is a chat service for example.
Why use WebSockets and not HTTP polling? it all depends on the needs if you know you are about to get a constant rate of messages polling might not be the solution for you, on the other hand, an open “pipe” with your server by opening a WebSocket just might be the thing you need.
For further reading on WebSockets, you can find here
For the Socket Rocket repository by Facebook, you can click here