最新消息:VPS服务器又从fzhost.net换回linode了,主题仍用朋友推荐的大前端D8

【已解决】Swift中建立websocket连接监听端口收发消息

Swift crifan 158浏览 0评论

swift websocket

swift websocket 监听

swift集成websocket库 – ___leng的专栏 – 博客频道 – CSDN.NET

daltoniam/Starscream · GitHub

最后相关的代码如下:

//web socket for receive message
//ws://jiandao.im:8080/message/{userid}/{token}
let StrPrefixWebSocket:String = "ws://"
//let StrServerWebSocketUrl:String = StrPrefixWebSocket + StrServerDomainPort + "/message/"
let StrServerWebSocketUrl:String = StrPrefixWebSocket + StrServerDomain + "/message/"
        //(2) websocket url
        //ws://jiandao.im/message/user-972b6796-cc82-4058-b29f-9007115116b9/9i8fu0uooq18tunpo9h6grp6gk
        let curUserWsUrl = StrServerWebSocketUrl + gCurUserItem.id + "/" + gCurUserItem.accessToken
        gCurUserItem.wsUrl = curUserWsUrl
    var webSocket:WebSocket!
    //var wsKeepConnectTimer:NSTimer
    var wsKeepConnectTimer:dispatch_source_t
    static var wsFirstInit:Bool = false
    func initWebSocket(){
        dispatchUserInitiated_async({
            gLog.debug("gCurUserItem.wsUrl=\(gCurUserItem.wsUrl)")
            //ws://jiandao.im/message/user-972b6796-cc82-4058-b29f-9007115116b9/9i8fu0uooq18tunpo9h6grp6gk
            self.webSocket = WebSocket(url: NSURL(string: gCurUserItem.wsUrl)!)
            self.webSocket.delegate = self
            self.webSocket.pongDelegate = self
            self.webSocket.connect()
            gCurUserItem.wsInited = true
            MainViewController.wsFirstInit = true
            gLog.debug("websocket \(self.webSocket) has inited and connected")
            //self.jpushSetAlias()
        })
    }
    func websocketDidConnect(socket: WebSocket) {
        //<JianDao.WebSocket: 0x7ffe09cbf9f0>
        gLog.debug("websocket \(socket) connected")
        startWsKeepConnectTimer()
        if gCurUserItem.hasLogined {
            if MainViewController.wsFirstInit {
                gLog.debug("is websocket, so not update all conversation")
                MainViewController.wsFirstInit = false
            } else {
                //later sometime, when after disconect then reconnect
                //so need update conversation list
                SingletonConversationTVC().updateAllConversation()
            }
        }
    }
    func websocketDisconnect(){
        if gCurUserItem.wsInited {
            StopWsKeepConnectTimer()
            gCurUserItem.wsInited = false
            gLog.info("disconnect \(webSocket)")
            webSocket.disconnect()
        }
    }
    func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
        gLog.info("socket=\(socket), error=\(error?.localizedDescription)")
        //websocket is disconnected: Optional("Invalid HTTP upgrade")
        //socket=<JianDao.WebSocket: 0x14fb1ec70>, error=Optional("connection closed by server")
        if gCurUserItem.wsInited {
            webSocket.connect()
            gLog.debug("try reconnect")
        } else {
            gLog.warning("not reconnect for websocket not inited")
        }
    }
    func websocketDidReceiveMessage(socket: WebSocket, text: String) {
        /*
        {
        "_id": "message-2f57ee77-6acb-4798-b5b0-ced3fcdf7331",
        "created": 1449802894811,
        "sender": "user-0e11abe8-e362-4311-8efc-7a2db70c2eca",
        "receiver": "user-4e21fc48-179d-4db9-a61b-eb2e7e2e033a",
        "type": "chat",
        "subtype": "text",
        "text": "网页端 从 班亮 发送给 马行 222"
        }
        */
        /*
        {
        "_id": "message-ec9736bc-4528-4d5f-bb26-e9f96d023cbb",
        "created": 1449820816829,
        "sender": "user-4ce697e9-b418-49e4-b827-cad735aaa827",
        "receiver": "group-1d316646-5791-4c28-8aea-783d18f929d1",
        "type": "chat",
        "subtype": "text",
        "text": "11"
        }
        */
        let messageData:NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
        let messageDict = JSON(data: messageData)
        SingletonMessageManager().processSingleMessageDict(messageDict)
    }
    func websocketDidReceiveData(socket: WebSocket, data: NSData) {
        gLog.info("socket=\(socket) , data.length=\(data.length)")
    }
    func websocketDidReceivePong(socket: WebSocket) {
        gLog.info("socket=\(socket)")
    }

【总结】

使用swift的ws库Starscream还是很方便的,核心初始化代码为:

            //ws://jiandao.im/message/user-972b6796-cc82-4058-b29f-9007115116b9/9i8fu0uooq18tunpo9h6grp6gk
            self.webSocket = WebSocket(url: NSURL(string: gCurUserItem.wsUrl)!)
            self.webSocket.delegate = self
            self.webSocket.pongDelegate = self
            self.webSocket.connect()

其中当前的类,要去实现对应代理:

转载请注明:在路上 » 【已解决】Swift中建立websocket连接监听端口收发消息

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
15 queries in 0.204 seconds, using 9.77MB memory