Open niksauer opened 6 years ago
websocket.onString { websocket, string in
do {
guard let data = string.data(using: .utf8) else {
// error converting string to data
return
}
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
guard let senderID = json["senderID"] as? Int, let message = json["message"] as? String else {
// missing required fields or invalid data types
return
}
if userID == nil && !chatroom.connections.contains(where: { $0.key == senderID }) {
userID = senderID
chatroom.connections[senderID] = websocket
chatroom.notify(event: .userJoined(senderID))
} else {
// user already has an active session
}
chatroom.send(senderID: senderID, message: message)
} catch {
// error serializing JSON string to dictionary
print(error)
}
}
websocket.onClose { websocket, _ in
pingTimer?.cancel()
pingTimer = nil
guard let userID = userID else {
return
}
print("closing websocket for \(userID)")
chatroom.connections.removeValue(forKey: userID)
chatroom.notify(event: .userLeft(userID))
}
@BigPen1s @xplip is our current chat infrastructure sufficient? please see liveChat(_:) in ConversationController.swift and backend ERM model
https://github.com/vapor-community/chat-example