I have two apps, client (iOS app) & server (Vapor app). I am trying to pass username & userID to server with webSocket when app connected to webSocket. The problem is... I don't know how to send params with webSocket, I'm only able to send data with message as structure, but that's not what I want.
My iOS client connect method:
private var webSocketTask: URLSessionWebSocketTask? = nil
func connect(completion: @escaping ()->() = { }) {
guard webSocketTask == nil else { return }
self.username = "Name"
self.userID = UUID().uuidString
let url = URL(string: "ws://localhost:8080/connect")!
webSocketTask = URLSession.shared.webSocketTask(with: url)
webSocketTask?.receive(completionHandler: onReceive)
webSocketTask?.resume()
}
My Vapor server method:
var clientConnections = Set<WebSocket>()
app.webSocket("connect") { req, client in
client.pingInterval = .seconds(10)
clientConnections.insert(client)
client.onClose.whenComplete { _ in
clientConnections.remove(client)
}
client.onText { ws, text in
do {
guard let data = text.data(using: .utf8) else { return }
let incomingMessage = try JSONDecoder().decode(SubmittedChatMessage.self, from: data)
let outgoingMessage = ReceivingChatMessage(
message: incomingMessage.message,
user : incomingMessage.user.name,
userID : incomingMessage.user.userId,
gender : incomingMessage.user.gender)
let json = try JSONEncoder().encode(outgoingMessage)
guard let jsonString = String(data: json, encoding: .utf8) else { return }
for connection in clientConnections {
connection.send(jsonString)
}
}
catch {
print(error)
}
}
}
CodePudding user response:
If you want to send data on connection you'll need to pass it in the URL. You can either pass it as query parameters (ws://localhost:8080/connect?name=Alice&username=alice
) or pass it in the URL itself (ws://localhost:8080/connect/users/<userID>
)