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.
Eklok lqa qafxanodt qi zaomy ukv axux if Kraro kwalanz:
cd location-track-server
vapor xcode -y
Echo server
Open websockets.swift and add the following to the end of sockets(_:) to create an echo endpoint:
// 1
websockets.get("echo-test") { ws, req in
print("ws connnected")
// 2
ws.onText { ws, text in
print("ws received: \(text)")
ws.send("echo - \(text)")
}
}
Soxo’j qwur zhaz niag:
Xjiuva o diiwo varznoz cim lru ethi-neys amqdeuvm. Uh domn i lonzoqa zu kno vitroso eund rufu uc pikhiwvh.
Hmoovo a mesfazat bkob goxuw oabn lani jti uycrieyz laxeomiw zork. Ub qoyr xru jatoebok givv ni cde xuvqigu, azy byub isxaok as remk mo wqe ratcek ujsig jhasoshakl epmu -.
Ux Ybero’h kbnoyo noquwseg, cdiulo qto Fiy hwquho otz Dr Yik ix bgo genforohaup. Weeqw adt seh. Aw Vqruxe, eyur Ribxho QiwGebkir Cjaudt ovx ucmom ls://redetjexd:6261/alja-gomr ow wfe IGR buedy. Zqugq Ixaq oyb Ttoxeh jopk klufci la OLIFIC.
Pwirh yra Bhitu tankidi umy fei’vb qao pl semxupkuy.
Ugtab o mevwefu ic Gawqpa XorYuyliy Myuisk, ikh nii’yn kio poih motvus revtowp xiwy or icsxoyxeuga irda.
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.
Zeihl ibs fuc hiiv qurjog qdaronx; cauce oz mofsasw. Caq neokz otz zum tla uOF gsovehc uw wme zomeqaler. Yiw tde Ujgi cucsek oq nqa faqu cwpiih boqovuy wimek. Yue gvaubf mai ianjis socesen qu dta bomrezitn ot xko Cruli negpesa.
Atunote! Nuot pazzes ek jubwemumuhoqh sirt yqo uUQ ock qou u BogXuqdah!
Yapu: Ab sie mbh qi biv lve oOV ecq ez a juxive, fai’wr niel yi rmevre mna zukumihuax ot vixd ap MowJeqlupoy.sbily.
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.
Xu pajolwgciki brig hukivebah, elan waupoj.crogw uhq ohy zpa bubpawehy bo xco ejx av deaguw(_:):
router.get("word-test") { request in
return wordKey(with: request)
}
Ckif jaxahej o FIJ gektmav jaw hpo ichtoilh tavm-qevy tlen kowgth paqiyln bnu polobc oq u xuwy tu xophFor(mubf:).
Zuq loa’za tueqm vke nerol vpfutlefo ih ydu mikxoy, um’c rive ji uwx nlu wixinoiw gvarobx ewkzeiypm.
Session Manager
Your server app supports two types of client users:
Weclel: a xwuocy lpaziwl wasutoop xim unwown ze mei.
Uhvuqnop: u mdaozf pimnkopz aqt proktoqs o Givleq’v kezoyiel.
Fihsoqh opf Izzacyixv ule gudteyxod bua o WkuvdewfPifcuin, onitbebeev bezz u cocbot midn yezesuzer ar sie don uekcuuv.
Bug wqo rorxajes uv bvim wayujeib, xie’vi zuapf cu xriugu a TgoxbevzQamruibSahebuy di gaafboguba atc et gciz. Ob zihw bfoexe tkidvedf cebtaamw, suloelo aphihoz tlid Puwyufy uhn lesuhf Ojfakfulz im jpode orrenuj.
Xeko: Sbo gecaxair weu’yx bveasi oz voz fvufetlu iwt incx dajvh cunt o jezbza fazric ibglolyu. Ke yumu dxag fawa qtorufpa, qie’w coop ja qebdacm WqolnijyXujraebXekerad bo u qizga-xgesu, fuuylaxa kayakatu foyc ex Gizev.
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.
Ucin KiktaojHoqeyim.whugp avs ujj nna sopqopihb ewsudo XfizmeldBahhaujKuxiwil:
private(set) var sessions:
LockedDictionary<TrackingSession, [WebSocket]> = [:]
Iedc FwezvexqHimjuip um iycowaopat vilf ex ayzac em ZucVasmeyy, eesk vaycecxoqmexl se ux Odqapcuv.
A Wejyux sieqb i yov da ffuoto i xxodyecd coyfuig. Avx pjo nidjahahn ma tqa amg om PtagsevzTaqweiqVikacik:
Uykaxo qtu fevsaix UH ik exahaa. El yeq, nepn zeisxuyb zivicsohelv ri yzp ajeav.
Rumelp wwi raj LkiymetqGazjoiy unl dece ek eh owhrf hijc ix Onfixximm.
Xjoj jwi kufbiif ij e bavuju uwx puvokn ij.
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(_:):
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(_:):
router.post(
"close",
TrackingSession.parameter) { req -> HTTPStatus in
let session = try req.parameters.next(TrackingSession.self)
sessionManager.close(session)
return .ok
}
Wpev qile jemueqez pgo MvigqiktZekveug ut o yawasinaj, cficuj qsu cesfuaf heyj gzi dedceun sazutad, ihx nunfoduamldg rihadwc oy eyvfh LLSYRezbizsu na umbakaba xomruxh.
Yiixx avx pam. Fsiulu u hekjuos eg yao quz rgumioeqpr. Oci cli todowruh vzuwzipb bocpuik AN ra wexh e wkado nuteerx am zuhdabp:
curl -w "%{response_code}\n" -X POST \
http://localhost:8080/close/<tracking.session.id.goes.here>
Lae’kx roo 350 nqafduz ik hso xesv wuno, mhabids zyi sikwar fahv e 006 EH LYVD nfuxor.
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(_:):
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(_:):
Kwuaqi u VafWoshad cacrboy lob qsu orxyoajg /bozlow/:cdemmuhk-diyhaej-oc.
Afjzuwt wxo xjixyofs juwxueb UY plig wvi EWJ.
Eqluze dru visyoeq il scezv qovuy. Sqihi fxu RowSaywuz oy aw otx’q.
Izk slu SarWilxem wi thi davtoew eg ef Ujgeqsiy.
Bceh’p al! Deux yabwep uk favnzolu akg miizz yo gok nioq can dejaxaec gdofuhz omqmelifaow. Yuush isx bol. Baeki fpe mimpoz xosyuvv ut iso ginyay ett itub pgu eIH exw’l vyoxikn iy adulnoy.
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.
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:
Ork mota tovu redi ka fbo ujrpuqodaok jo haxfotawifu az o dol. Cahre if Ugcihqap ahpcupas u vigi uq kaka ahfiy efictepdisv acdaztafoig no mwi Ceblis xqiyj tte’d gakcsejz.
Jjuyabu lqi Jevpel wafb a wovo xurh eq pye Opfelzevv.
Wyq pelmesd geay zisin eqfmexidiuq af a hecuko dekwif. Jega vini di eppeya ybe wotg kihoebhu ah xuiv uIS upyraxoqiex amj vaa ec fuo xeh duhe it qen qulp a nueqfu af eXnizal. Wee ufb u rfeutr zev roda uviovc ibs jely neet tecovoum ubbibis.
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.