Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Connect to a WebSocket

This video was last updated on Sep 15 2022

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.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

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")

Reviews

Comments