Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

Websocket – swift客户端

2019-11-19 04:20:02

import UIKit
import Starscream

class GameViewController: UIViewController {
    private var socket: WebSocket!
    

    override func viewDidLoad() {
        super.viewDidLoad()
        

        socket = WebSocket(url: URL(string: "ws://echo.websocket.org")!)
        socket.delegate = self
        socket.connect()

        
    
    }
   
    deinit {
        socket.delegate = nil
        socket.disconnect()
    }

    override var shouldAutorotate: Bool {
        return true
    }
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            return .allButUpsideDown
        } else {
            return .all
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Release any cached data, images, etc that aren't in use.
    }

}


extension GameViewController: WebSocketDelegate{
    func websocketDidConnect(socket: WebSocket) {
        print("connected")
        socket.write(string: "hello")
    }
    
    func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
        print("disconnected", error?.localizedDescription)
        //performSegue(withIdentifier: "websocketDisconnect", sender: self)
    }
    
    func websocketDidReceiveMessage(socket: WebSocket, text: String) {
        print("receive msg", text)
        guard let data = text.data(using: .utf16),
        let jsonData = try? JSONSerialization.jsonObject(with: data),
        let jsonDict = jsonData as? [String: Any],
        let msgType = jsonDict["type"] as? String else{
            return
        }
        
        //2
        if msgType == "message",
        let msgData = jsonDict["data"] as? [String: Any],
        let msgAuthor = msgData["author"] as? String,
            let msgText = msgData["text"] as? String {
            //msgReceived(msgText, senderName: msgAuthor)
        }
    }
    
    func websocketDidReceiveData(socket: WebSocket, data: Data) {
        print("receive data", data.count)
        return
    }
    
    
}

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *