-1

想象一下我们有 websocket 的聊天服务。我们将消息作为带有属性的 JSON 发送request_id。服务器捕获我们的消息,将其保存到数据库并id通过将另一个数据发送回客户端来返回消息request_id。客户必须找出与此“响应”相关的确切“请求”并将数据保存到本地数据库。

例如:

  1. 客户端发送消息:
{
  "request_id": "1st",
  "content": "first message"
}
  1. 服务器接收消息,保存并返回新消息的 id
{
  "request_id": "1st",
  "message_id": 123242139857814
}

与 Alammofire(使用闭包)不同,Starscream lib 不提供这种机制。我正在寻找与 CoreData 和 RxSwift 兼容的解决方案。如何在不丢失“请求”上下文的情况下处理服务器的“响应”?

4

1 回答 1

0

有很多方法。例如,您可以使用下一个代码

class Mapping<T: Hashable, U: Hashable> {

    typealias ForwardKey = T
    typealias ForwardValue = U

    typealias ReverseKey = ForwardValue
    typealias ReverseValue = ForwardKey

    typealias KeyPair = (ForwardKey, ReverseKey?)
    typealias ValuePair = (ForwardValue, ReverseValue)

    private var forward: [AnyHashable: AnyHashable]
    private var reverse: [AnyHashable: AnyHashable]
    private let emptyHashable = AnyHashable("")

    init() {
        forward = [:]
        reverse = [:]
    }

    func insert(pair: KeyPair) {
        if let base = pair.1 {
            forward[pair.0] = base
            reverse[base] = pair.0
        } else {
            forward[pair.0] = emptyHashable
        }
    }

    func update(pair: KeyPair) {
        insert(pair: pair)
    }

    subscript(forward key: ForwardKey) -> ForwardValue? {
        return forward.first(where: { $0.key.hashValue == key.hashValue })?.value as? ForwardValue
    }

    subscript(reverse key: ReverseKey) -> ReverseValue? {
        if let result = reverse.first(where: { $0.key.hashValue == key.hashValue })?.value as? ReverseValue {
            return result
        }

        return forward.first(where: { $0.key.hashValue == key.hashValue })?.key as? ReverseValue
    }

}

struct Request: Hashable {
    let requestID: String
    let content: String

    func hash(into hasher: inout Hasher) {
        hasher.combine(requestID)
    }
}

struct Response: Hashable {
    let requestID: String
    let messageID: String

    func hash(into hasher: inout Hasher) {
        hasher.combine(requestID)
    }
}

class WebSocket {

    private var callback: ((Request, Response) -> ())?
    private let mapping = Mapping<Request, Response>()

    func request(_ request: Request, callback: @escaping (Request, Response) -> ()) {
        mapping.insert(pair: (request, nil))
        self.callback = callback

        // Send webSocket message
    }

    // WebSocketDelegate
    // Since you are using Starscream
    func websocketDidReceiveMessage(/*socket: WebSocketClient,*/ text: String) {
        // Parse text to Response
        let response = Response(requestID: "1", messageID: "2")

        if let req = mapping[reverse: response] {
            mapping.update(pair: (req, response))
            callback?(req, response)
        }
    }

}

let webSocket = WebSocket()

webSocket.request(Request(requestID: "1", content: "A")) { request, response in
    print(request) // Request(requestID: "1", content: "A")
    print(response) // Response(requestID: "1", messageID: "2")
}

webSocket.websocketDidReceiveMessage(text: "")
于 2020-01-19T21:43:34.323 回答