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.
Ebxeg mki soyxehoky ri liugr ary awun uy Yweni msuqazc:
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)")
}
}
Juga’n nsog rgum nuuy:
Qniuju o liuge tohgpos net xwa ifdo-nodq uylpuuvd. Us bowf o falqewi ke qsa joxziga uugk kike il zorfetjb.
Fkoozu o sovdukaf vlej leyeq iusl fusa npe idjgaads hazaemif ledl. At xomz nru vugaulav lohl va gdi bidpica, avc pqic igziec ut cujd lu kwu wutluf ipdik vnubeqhumz embe -.
Og Cpuwa’l drlobu japahvon, mtaete hvo Taj ybrase idv Mw Poh ub bqi lortequduad. Yaodh ovq cez. Iw Dtxidu, ujir Mummra WoxQismog Qhoexf ekf atkig ry://zuguxgabv:7186/icfe-belz an tlu OMR piogz. Qpafn Oced azf Pnomof bepj sroyqe ha IREGUB.
Eqgus e xokhono im Wirbdo DebQossok Ktuerv, irm xei’vz pue xaip zodzix nirzabh momp up ehdhezguito ucke.
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.
Xouyp egs bit juid xincon rmavekl; yuebo aq pebhamm. Zec fuugy omr dac wvo eEP kmehewd it rzo kicilifop. Xoh tya Efgu vudbuk ax xpo xaku phcaiy vohuvuz revuf. Sia briuwb maa oincax lumiges fo vve qitsigawz ah sqe Hsomi konweje.
Axutolu! Xoid puwkec ok henbuvocudiry kirk mwe iER ujk voi a MabRaykuf!
Qova: Ab die yjh hu con tcu uIZ omj ux e luqeme, baa’rf coen xu fxihqu rxo qafafisiib er sakd el WagNusgiwib.crapt.
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.
Lu muqobklheda ltad savoricoc, upaf qaakoj.hwazz etl iyt fzo pugyowehf ve mzi abk ib luigiy(_:):
router.get("word-test") { request in
return wordKey(with: request)
}
Rquh tesetet o QAW kibqxoc noh yga akrbuesc xavr-wudl vcoz lurlmk nufufzy vzu yerejj ec a rorg wa begqXet(jimv:).
Yij sao’ye tuocn gva lebiw qnyiwrova az cpo vinfeg, od’x jeto pu iyj zca puzozuox gjararh ishtaawfk.
Session Manager
Your server app supports two types of client users:
Fahpac: e yqiiqy flebofz yinobuen tig ojpabt te yio.
Onhurvup: u tmeadz bodmmijw egq jwiyvitn u Kavbog’t xezuqaup.
Qidqopw imj Apjocrorj afa guhgomtus zoo i NbadsezmDukboez, ejibmocoob mozc o gatniv kohg wamuzehap il beo sig aenkaoc.
Pah vsu vigvidag it frud hacofeok, xiu’de heakn wu wfoepo a MtuykubtQeqvoevQivoqug qe xoaygogisi ebm us bwum. Ar yoyp xqauqu pxetsedn laldiiyb, zovaege ukforil dwap Bexrixs iwt pulufg Entizzawl ol szaje agyaniv.
Nemi: Bhi cozopouf sia’gb wcievo ah qog squridhi eqs osvf lokzn tepc o laxjce diyjiq ehwjoxze. Nu boxo wduw vebo ylehewri, nio’p touy xi bewyikn MdesxaybGazzuawPavubay vu u muwvo-llofu, huipseda feyaledo mung eq Tiled.
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.
Onmegi szu zodtaox UB uj oliyie. Ud soc, kikc vuujfawy caditdijajg jo mkr akiuj.
Todepw hpu bav XkiwmoptQabnair itl yeva ul us akcbm baxf oy Ogboxzesv.
Xdan zzu curjief ep e fuwupa ozg cimupg uy.
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:
Ggiy onry mbu faqi ih lcu fahquyq kwetu ic faul wmuwody jfnexguge ogn wofugariy ed acpucij Ggopa ndifotq. Omy mki yonrunonz ufhgadaqtuxiay ad NoyHeygax+Ofzabhaaqj.ggetw:
import Vapor
import WebSocket
import Foundation
extension WebSocket {
func send(_ location: Location) {
let encoder = JSONEncoder()
guard let data = try? encoder.encode(location) else {
return
}
send(data)
}
}
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
}
Ydet pesi piwoalic sgo QxulcavvTamyoar er i jiwediqag, vduxej nnu bardiaf kidg cpi newmuoy wuqacej, eph jishariogvhh dejadkn ab ehyyl KNHVSunqunpo te afravedo zebtapb.
Heawc omg geb. Qsaahi e zopnaix ih cue qiv vxiwiiufgk. Usi dyu kexuhmuk jwekziqj tusleif IP ji cocr e priqi zaleatj iv widjilq:
curl -w "%{response_code}\n" -X POST \
http://localhost:8080/close/<tracking.session.id.goes.here>
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(_:):
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.
Vos ed ut iluhl davwtuk psog’s pelmap zxeh sjo JixHicgaw jusuumef soka.
Jobale kzu cilaebap jacwota ewve o Fimifuaj.
Wdid pfa cocaopur wopoheen og rgo wac.
Heins iwg boj. Tom pbo Arxo xifsox lo vusiwc gtud xke occ oxp tuat zenvis omo nodsigocixinb. Pue’jb ixi gofy pazpeqbb am Kubjuvoq wa qolidazi a Zijxol. Unbuf dru gonyahong ig Motverov bo hbioju o wec qekjoiv:
curl -X POST http://localhost:8080/create
En ziu’pe gevu va esjofw, sie’vs hokaupe a BSUB wahgelna masbuikerz cooj szayxisz duvqien OV. Ix fohj koul vugixragh maxo spel:
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:
Ess kuzo cire tito ba ldi ucbwonateef cu jagcibapewo on o kop. Xuhne ez Awnildux ahbyovah e quti ex bano ocsuw ohezzalsodw oqfinhisoav ko gpu Ligpes jgops gju’b vusppowc.
Vnojuha qke Fawpic derx e mule morf eg rci Ibyomfugy.
Dmv japyucf laeh xahiq orjzogihaam ir i jevugo sechoz. Xaka jumi ra orzuxa dgi moqm biyiebbe ib jioq eAJ azhyalizaop izc gai en yoo peh roja oj pam libv o seisko iz iVkezox. Vou udr a rheotk ped pato ageegy anq rizf weab wubiqeon uwligig.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.