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

Next
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've reached locked video content where the transcript will be shown as obfuscated text.

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.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)")
      }
    }
  }
}
@State private var webSocketTask: URLSessionWebSocketTask!
func setUpSocket() {
  let webSocketURL = URL(string: "ws://localhost:8080/chat")!
  webSocketTask = URLSession.shared.webSocketTask(with: webSocketURL)
  
  listenForMessages()
    
  webSocketTask.resume()
}
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()
    }
  }
}
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 {
      print(error.localizedDescription)
    }
  }
}
Button("Send", action: sendMessageTapped)
  .padding(.trailing)
.onAppear(perform: setUpSocket)
.onDisappear(perform: closeSocket)
ws = new WebSocket("ws://localhost:8080/chat")
ws.onmessage = function(e) { console.log("from server: " + e.data) }
ws.send("Hello from Safari")