When everything else is too slow, and your demand for information is high, set up a Websocket.
An iOS-to-server TCP connection normally is constructed with something like NSURLSession. The connection is initiated with a three-part handshake and once established, the client makes requests and the server answers.
But what if the data changes on the server? In the normal situation, the client doesn’t know about this unless the client GETs more data. The client has to request the information again. And what if the data is changing very quickly — like the prices of thousands of stocks in the stock exchange, or the prices of hundreds of types of cryptocurrency? Or what if there are 10 family members in a group chat excited about their NFL team in the divisional championship?
In these cases, the iOS app doesn’t want to have to request the update and then wait for the information. Instead, the app and the information source need a way to communicate in both directions and in real time.
Websockets provide this functionality. A websocket provides a persistent connection with bidirectional messaging until one side closes the connection.
In this blog, we’ll get quickly set up with a websocket that connects from your browser to a real server. And you’ll exchange messages in real time.
Here’s the summary of what we’ll do:
1. Download Docker for the Mac.
2. Set up a websocket on a server running in your Docker container.
3. Connect to the Docker container from Safari.
4. Next time: Download Postman for the Mac.
5. Next time: Set up a websocket in Postman.
6. Next time: Have a real live websocket chat between Postman and Safari and see the conversation in the Docker container.
1. Download Docker:
Go to Docker.com and download the appropriate version for your intel or apple silicon mac.
After installing, follow the directions here:
https://docs.docker.com/desktop/install/mac-install/
which I summarize as:
$ sudo hdiutil attach Docker.dmg
$ sudo /Volumes/Docker/Docker.app/Contents/MacOS/install
$ sudo hdiutil detach /Volumes/Docker
Get Docker running on your mac.
2. Set up a websocket reply server with docker.
Docker is a container emulator. It’s analagous to using Parallels to run Windows on your mac. Only the docker container is built to run a linux or windows app, or sql server or websocket echo-server inside it. And on any platform.
Run the following command in your terminal to start the echo server:
docker run –detach -p 10000:8080 jmalloc/echo-server
Now go to Safari and enter the following
http://localhost:10000/.ws
You should see an interface that will allow you to enter messages and have them echo back to you.
Tomorrow we’ll add Postman to the conversation and you’ll see both Postman and Safari chatting with each other in the Docker container.