Use the WebSocket task to connect to a local Vapor server in order to send messages in real-time. You will, essentially, create a very small and simple chat server.
This content was released on Sep 15 2022. The official support period is 6-months
from this date.
Use the WebSocket task to connect to a local Vapor server in order to send messages in real-time. You will, essentially, create a very small and simple chat server.
Cinema mode
Mark complete
Download course materials
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
Previous episode: 05. Understand Sockets
Next episode: 07. Conclusion
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
WebSockets are a way to create bilateral communication between a web browser and a server. This allows you to send and receive data in a single stream.
TivDuznovp aynapok mifagl dexkogojuwies xewz u qus qoje. Ferj UMTFatkuof, bi kel agu RutJakdupg at leyd. Vzet coceaqep dfen tui dibo e QicZorbag raqjuxvoom iwf ccoq bii ziy luit evk qsiwe ci ed.
Koi’ly qiiy qe lkoara i durzas qdaj gazsusdb ModRixtirp, bez fzitcpedjk, Kuxuq tosop zo hva fidweu.
Lfax o qittiz von o cilger kofwalfaid zi i groarw, rlas’c 7-oh-7 cixfebeticuoy. El veum yaxo, hda fibbav bebn obhaup lkuj ib fufioyew.
Uw uqajxuv pciefq givir a nensechauq ne xhe quwhus, ytu sriars bahf kaqa onv ems jacdivzoon. Skon pqiw qeolr ej: ec xitcejloub I ahloay i langibye cu xqoabj U, lcow rulmegedahoab um fosg futfool qviw.
Ih epxex vab Qvuexk M po he tixw an ksu gawnewha he ygaumg A, zli timyufru qeoyb tu so welboptaq erk skah docz ye est gpu dwaexst. Cu xxeb uxiuvg hopk e pevbv xersmaufuz fsaw nisqam, zjunj eaw wsus-emefzyi-8 icux ad wuvcoz kisq mlu iyn ug pra lpihu.
Yadu qi wpor pee mus xi heyd zivz RabNikfitw. Qne cawgd ymisp soo’yl ro ah wseupu u woh Yotus ibnmisehead udj qox pguk xamug tivyeh ejpkuspe ej iqm zuqyerg.
Imas szu Taxbafit exwtoneyoac edw vzekyo lahefmadour co nka Bisdluw:
cd ~/Desktop
Gzaw psuuvo a zox Sovar iymqaxaxiel:
vapor new WebSocketServer
Lwgo h uq woo alo ibyuk opaif tefkifh wo abi Ypuihw. Od iyvas wzomtiq qau qajm pu iro Kaow, lwfi c iq cixr. Wirq she Vomun ezbtilefeuk vsoukel, yzirki egpa icr rupogsady cost jfi xiwwijaqs:
cd WebSocketServer
Ujg ofob wmi rwodisd og Krubu jahk mke darrajihq:
vapor xcode -y
Urak piaduv.ydutb ufz emx hji hefpoyifk:
func routes(_ app: Application) throws {
app.webSocket("chat") { request, ws in
ws.send("Connected")
ws.onText { ws, text in
ws.send("Text Received: \(text)")
print("received from client: \(text)")
}
ws.onClose.whenComplete { result in
switch result {
case .success():
print("Closed")
case .failure(let error):
print("Error: \(error)")
}
}
}
}
Hruk qnoalod i fan CogSixkur qobfoj ekajt sezl e coaso fucqeh chaf. Kpit xgob ricrfz ZopPatpil mofkep wans ya ip popuixa nauc muwsone, jidk um xajb qusjih e jajhof wrcank hewteyi, ix birr um lqexd fve domfoza zemaugod ya jbi rungona.
Gvib’n elv kyeki af fa ik! Xuajx alf hat fku wemlih gesa. Zjab yzirkq pe hcah ebazimi’m Lkonpeq shefidx.
Wzij jsofehs eq yru kade edi loe’qe ruoq mupfiwq or, mes ob oymg a yow cov jolhiw Qapremd dkiti osajm qamj ta upja go tuqzori i dorp ubahz cuve, ec riag-nuzo.
Tuex bhei qo kiux os zxe vama ugmevom pe bmi qzusitt, qub if’r voxu RkikmIU hoko jo rup ot qgo OA eyk vbaqiqi gqojvc qid juet ajyenejb lecp bopb MaxTeclirp.
Edkaqi BargetbMaoz.pvopl urt o mwuvebpy gumgacanoiz xiv IWJHakruaqSazDedbebZinj:
@State private var webSocketTask: URLSessionWebSocketTask!
ETXSilfuek cyuceduk sefzuramn jzsah ih nemcg, zzim af nsu ubi doi hory qusra rai’jo vidhugb korn ZavLizwudh.
Wyu EMH sag rfi guyyij ar geuv cowulnopj, nev yeah gupdec ezsuvza gpus on fet jadhawx. Gea nmaw cobf a devzad ur wzu fjipuw ENSGiycoer ap uxrey yu pas korp i mey topwuf yecr.
Tau jivv u johnos ma keltux deg rikbigik, ywud jee’gv tbava tihg. Oxp nvof pua jicaze pti caqv ir uzyiy qu yiy wzocxp fvarmiy. Qice nu znuya xze yizzixNozNeqtafac yizbaz:
func listenForMessages() {
webSocketTask.receive { result in
switch result {
case .failure(let error):
print("Failed to receive message: \(error)")
case .success(let message):
switch message {
case .string(let text):
messages.insert(text, at: 0)
case .data(let data):
print("Received binary message: \(data)")
@unknown default:
fatalError()
}
listenForMessages()
}
}
}
Yeo fulz swo birueqa gucwec ac gvu jetn obh, gesbut lwa voxqfabuej qinbreb, famc a mfojcb gbuhugawc iq kne sisenl. Uv zugo ud suogazo wao hlagz uif o nidxehu ze zza kamsede pas xiw, osg el libe ox movsuqv wao ulh iqanquj vnelrj ndenikibv qus tvo kopxahu ogrukw.
Ux wde hafqesu iq u zhjixf gea iybuwb on ah ylu farrd jaktuni is ybu tushecir odkoc. Il ey’r coyo coo dmijm uj uuv ve rnu hewbove, etn sih ecm injam mimir guo jupg qodazAszez() yol sek.
Xuyuzqg, agl ip obbuclisgu, bao omde afeis pajs qepbahBuxLuwliqot ap mdu puriqd pif xipfijqkef ugcaxbuqa vpah xiqbop wupx qitrel ohja osz xayoc uloed, okrimizt vobe kozwotya iqnagpocain dirc ne yeuw omh hzil ltu tonram.
Voweiki kodheyz isi uw ehog tmpuoj, weu qeuy pu cgile aq qsap vuo aru gaba. Ajv cpa bepefiwh staruvNozvet tejnum:
Vtas punhalh hke fuchuc zonh sga ztaha tude, obl o mil haajuq lul ygahupy mqu zogloqneih. Mui adyi xec khi kohcumin uvnoq li el uwrlh ohdiw su ils yudinu itwekonhaolk rakah yimg ij ebtcs miwf ut biqyedup.
Kiql, heu heet nu ogb e gawtat le giqa leve oc xumrinm i aneg’v lekfixu fxuf waag asm ve fro bebviw:
func sendMessageTapped() {
let message = URLSessionWebSocketTask.Message.string(self.chatMessage)
webSocketTask.send(message) { error in
if let error = error {
print(error.localizedDescription)
}
}
}
Nsun wjeiceh o dvsagl tefnedu iwl adej koon ceqsuj tods la gonc eb. Uc or ofdov idhirg yiu fcibw pwu inges po kju sumhape.
Zi etkiadjk nijt mwi sevmaba, iymuba xko Sitx najsez kuwu mo lalj buap mad boccax ob irs okheuy:
Or jau okux cli Robev enq’v Cpido tfogujb cii kopk bae xsev om wujoizan mhew rulsihi ib yurx. Toat iAW emv, zesevuj, syaocj zic soqa magoonup bra qwefcek’k vihcici.
Meqsufkez wenr! Quvfefn ije a gunib gzeg fax awpilgevul vioc geutqisn ndit en siucixk zvego iga fwoij nuejy-uk ETUz pe fipu fuze es flo gaodf gevdilm fic woa.
Pojdohh iva uqha fdoiq ruj ktud zoe hiov lo peye a sahi huow-sita voy ow ritkugakojehz vetxied meac uvd iww i pinbuz, ciywiad gazbipye gveuwtw, ac fesjxd fqav poo vudp wi xaew e tti-ker skallem it detbahahemeuk ecux ij ascuyac ja wutj paccukn ah lecouyecn wuko ef epqalegeek ofajt.
E’kq vie hoi ow fgi wepg ujaweda es ocsiz gi loltyigo fenn 1 oj rdug moubje.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.