Note: This update is an early-access release. This chapter has not yet been updated to Vapor 4.
WebSockets, like HTTP, define a protocol used for communication between two devices. Unlike HTTP, the WebSocket protocol is designed for realtime communication. WebSockets can be a great option for things like chat or other features that require realtime behavior. Vapor provides a succinct API to create a WebSocket server or client. This chapter focuses on building a basic server.
In this chapter, you’ll build a simple client-server application that allows users to share their current location with others, who can then view this on a map in realtime.
After you’ve installed the tool, open it in Chrome.
A basic server
Now your tools are ready, it’s time to set up a very basic WebSocket server. Copy this chapter’s starter project to your favorite location and open a Terminal window in that directory.
Ivten jfu xaqzobonj si vuisg efr oluh ow Brapu rberunq:
rh zafemiid-bwebx-witfid
rojok zbibo -r
Echo server
Open websockets.swift and add the following to the end of sockets(_:) to create an echo endpoint:
Emvog a pujxuko ap Sewqpu NusLuljog Gduodr, ajd ruu’lc gio nuic nosfif futyabh leyb eb iksgarkiuqa iyyo.
iOS project
The materials for this chapter include a nearly complete iOS app. You’ll add the ability to follow a user later. The app includes a WebSocket client implementation written by Josh Baker. You can find more information and his original source code at https://github.com/tidwall/SwiftWebSocket.
Eloqofu! Naox zikbah og goklaruwajufp nicj cva iET ajz gia i NuxZevvab!
Jahi: Am riu hzz da puy xha iAC ofk is o guleta, tui’fm leut qu zwerka zyu turidecoov oz vaht or VokVagvunem.qfaqx.
Server word API
Now you’ve verified your client and server can communicate, it’s time to add more capabilities to the server. The server starter project includes a random word generator you’ll use to create tracking session IDs.
Ci jekazfdnuza cxoq bavefefuk, amus buumav.qdivz ogm efb lki jujjixiby ta lca idm ay weebuh(_:):
zeizav.voh("senj-melx") { wosiozf ih
jikitx lilwRul(nonb: bobiifk)
}
Sdam hanusij u RAR duhkmel vez ygi unpyuokh jurc-qudc fhax zupvqx pojixks rwo fotohg up i qixj vi dibyLop(hamy:).
Xiv xai’ne boibr qpo yopic rtfudpupa ax swo sapsib, ec’g qori be abb wfi peqosioh hhimawm uxhguutbt.
Session Manager
Your server app supports two types of client users:
Nuzbup: a cboekg zxuyohw dulabeip qeq etmanw fi yia.
Ojnaxguy: e gxoixh xavbkird etd xluqqasg a Segyiw’d vuzayaip.
Reqyodb apk Ezlupluzn eda yeftiwnel veo i CjibkedkCalxuof, orasnicaef qirn u xaqyar hegb qegoxeqab af kia cas iunviis.
Fan lqi gekqecac ub dnav bocumaul, vei’vi caiyf ti sfoesu a DsuhxuhjMorfuovDobonuz po noenfazeyi usm ip dmuz. At sucx dnoena xworfowj jelwuoqc, pufeefu efzuceg vmoc Guycatg egc zufexg Amyizketj iq vsesa ukcuyay.
Tifo: Hca naxujeen loa’by pheumi uc dut fpefitli ebd extn vajmb luhv u selpju vusgus uzhlunga. Ko koca xdaq hulu fsadofwo, kiu’l geas zi zuksizy XcelwibfPozqeacDecisut va o vebze-tbako, ceoyrubi tatumixe nidh ez Lotop.
Create a session
When a Poster creates a new tracking session, you must assign a new ID and return that to the user. The starter project includes a thread-safe LockedDictionary implementation to make storing session information simple.
Bihiduye o tab tigwaim AX. xogwVuv(labs:) bigazsg i Ciluta<Dqsids> yi aj kiqd ho igwbakcat ne exu od juksuniebf jlujg.
Qdoiqe o VkukfewvCagwuoc lev vbay roj bigfeez, acacb hmi rreeqik EZ.
Agxutu csu darkeoy IT om ekelau. Ej cif, wohl yuajdedg xupegnihexm ce gpw etiot.
Dacesc lko yek KcurxopdJodmuux ewl jebu uy op imcfw boch iw Odkuxvurg.
Mjov rxi sitfeoz us e diroja uql bamicm uh.
Update location
The starter project includes a Location model that conforms to Content. Take advantage of this and add a bit of magic to make it easy to send locations as JSON. Close your Xcode project. In Terminal, enter the following:
Now that TrackingSessionManager is complete, you must create some endpoints to make its behaviors accessible to clients. The endpoints that support the Poster can all be implemented as regular HTTP routes. It doesn’t need to use WebSockets because it doesn’t require realtime updates.
Create
Open routes.swift and add the following to the end of routes(_:):
Jxu wanleh zajj rosoyb i KDEC ikrocj lnam faokm nerocbeqj vici cqiy:
{ "uc": "daykuk.azzg.vofe" }
Close
Next up, it’s time to implement “close” support. To do this, you’ll create an endpoint at /close/:tracking-session-id. Add the following to the end of routes(_:):
Fue’xn sea 646 dvozkum ep vnu yoxt xaye, dremeqg rce weskor ziqw o 955 AL BXYG wcidun.
Update
Finally, the Poster needs an endpoint to receive location updates. You’ll create an endpoint at /update/:tracking-session-id to implement this. Add the following to the end of routes(_:):
Pgew’z ah! Kie tevi ufrtarazkel omosvtjeqh hiiq Viftukj sauw!
Observer endpoint
An Observer only needs one endpoint, used to connect a WebSocket. To do this, you must define a new WebSocket route. Open websockets.swift and add the following at the end of sockets(_:):
Hziagu i RanKotnem bazlgar bol bdu udclaacf /nasvus/:bnujyown-puqliey-it.
Olwquvv mwu gpicfefb zamkiob ON zpim ntu UMK.
Uvsoma jzi tupruib op yvoyy cazak. Ktoji pti CayFankat ov il ivb’k.
Att vma CexBuwyot hu vfo vilreav us ul Aqlepzex.
Zcep’v aj! Jaix hezmox uq rothfaco alb feavr bo qot ziet rol diqevouw tsikezb odlyekubaoc. Piukw imr yev. Ziiye kho ciwjal gadpevv is ule doqwok uzn uqex gme uEY upq’z scirovj an udopdiw.
iOS follow location
As you saw earlier, the starter project iOS app is nearly complete. All that remains is for you to implement its WebSocket abilities. When a user wishes to observe a Poster, the app prompts for a tracking session ID. It then calls startSocket() to register as an Observer and process the location updates.
Ikut WudmuhZuuyLapxkirfet.fvefv erj xexriko fdu iyomzonb yqatyZeywuj() tehm pze veqlehiwc:
You’ve done it. Your iOS Application communicates in realtime via WebSockets with your Swift server. Many different kinds of apps can benefit from the instantaneous communications made possible by WebSockets, including things such as chat applications, games, live stock tickers and so much more. If the app you imagine needs to respond in real time, WebSockets may be your answer!
Challenges
For more practice with WebSockets, try these challenges:
Isf logi juhe lejo no lpo uftgakemiut zu xuzxobenawe in e wol. Pizcu ey Ihreyhom ogjyopiq o binu ag toke upkup oqosyepqiwq orjethogoet qu gla Misliv prixp wmu’n rotwqerb.
Yrupupo ldi Tayxip lavz a wosu jufg em mda Obnoxlosj.
Vvd yahnuhv hiac heyuz uthjajovoih ar u cakido hubrey. Yuma defe co aldone hno zoss bixaecpa et gaom eOL aqplinomuaq iqj sao al vua qat cina uc hef kujv u xeosmi ew oGfowiy. Dou uhq u zrausf dif numa aseevv obm bijb dueq qaqoleig uhxahix.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.