Advanced Networking with URLSession

Sep 15 2022 · Swift 5.6, iOS 15, Xcode 13.4.1

Part 1: Upload Data, Background Downloads & WebSockets

06. Connect to a WebSocket

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
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.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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.

cd ~/Desktop
vapor new WebSocketServer
cd WebSocketServer
vapor xcode -y
func routes(_ app: Application) throws {
  app.webSocket("chat") { request, ws in
    ws.onText { ws, text in
      ws.send("Text Received: \(text)")
      print("received from client: \(text)")
    ws.onClose.whenComplete { result in
      switch result {
      case .success():
      case .failure(let error):
        print("Error: \(error)")
@State private var webSocketTask: URLSessionWebSocketTask!
func setUpSocket() {
  let webSocketURL = URL(string: "ws://localhost:8080/chat")!
  webSocketTask = URLSession.shared.webSocketTask(with: webSocketURL)
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:
func closeSocket() {
  webSocketTask.cancel(with: .goingAway, reason: nil)
  messages = []
func sendMessageTapped() {
  let message = URLSessionWebSocketTask.Message.string(self.chatMessage)
  webSocketTask.send(message) { error in
    if let error = error {
Button("Send", action: sendMessageTapped)
.onAppear(perform: setUpSocket)
.onDisappear(perform: closeSocket)
ws = new WebSocket("ws://localhost:8080/chat")
ws.onmessage = function(e) { console.log("from server: " + }
ws.send("Hello from Safari")