zoukankan      html  css  js  c++  java
  • 【Swift】Starscream 实现socket连接

    import UIKit
    import Starscream
    
    class ViewController: UIViewController,WebSocketDelegate {
    
        var socket: WebSocket!
        var isConnected = false
        let server = WebSocketServer()
            
        var button1 : UIButton!
        var button2 : UIButton!
        
        override func viewDidLoad() {
            super.viewDidLoad()
    
            configureView()
        }
        
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
     
            var request = URLRequest(url: URL(string: "wss://5tdk1djuz1.execute-api.us-east-1.amazonaws.com/Dev")!) //https://localhost:8080
            request.timeoutInterval = 5
            request.setValue("eyJraWQiOiJMYjg3YnE4cHhTdk1oZmZSb1BGbUZSakh1bXR4R1BaTWFDTUErSElSQUQ4PSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJjM2YxNzQ2Zi1hYjMzLTQ4NGMtYTRlOS05NGU1MmEwNTBkNjMiLCJldmVudF9pZCI6ImQ1YmE1OWNmLWYzNzctNDY5Yy1iODc5LTQ2Zjc3YTFkNDJlZiIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiYXdzLmNvZ25pdG8uc2lnbmluLnVzZXIuYWRtaW4iLCJhdXRoX3RpbWUiOjE2MTkwNzU3ODAsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy1lYXN0LTEuYW1hem9uYXdzLmNvbVwvdXMtZWFzdC0xX1lDVHRIS3o4ZyIsImV4cCI6MTYxOTE0Nzc4MCwiaWF0IjoxNjE5MDc1NzgwLCJqdGkiOiI3ZGI0ZmYwNi", forHTTPHeaderField: "accesstoken")
            socket = WebSocket(request: request)
            socket.delegate = self
            socket.connect()
            
        }
        func configureView() {
            button1 = UIButton.init(frame: CGRect(x: 50, y: 100,  200, height: 100))
            button1.backgroundColor = .red
            button1.addTarget(self, action: #selector(writeText(_:)), for: .touchUpInside)
            self.view.addSubview(button1)
            
            button2 = UIButton.init(frame: CGRect(x: 50, y: 300,  200, height: 100))
            button2.backgroundColor = .red
            button2.addTarget(self, action: #selector(writeText(_:)), for: .touchUpInside)
            self.view.addSubview(button2)
        }
            
        // MARK: - WebSocketDelegate
        func didReceive(event: WebSocketEvent, client: WebSocket) {
            switch event {
            case .connected(let headers):
                isConnected = true
                print("websocket is connected: (headers)")
            case .disconnected(let reason, let code):
                isConnected = false
                print("websocket is disconnected: (reason) with code: (code)")
            case .text(let string):
                print("Received text: (string)")
            case .binary(let data):
                print("Received data: (data.count)")
            case .ping(_):
                break
            case .pong(_):
                break
            case .viabilityChanged(_):
                break
            case .reconnectSuggested(_):
                break
            case .cancelled:
                isConnected = false
            case .error(let error):
                isConnected = false
                handleError(error)
            }
        }
            
        func handleError(_ error: Error?) {
            if let e = error as? WSError {
                print("websocket encountered an error: (e.message)")
            } else if let e = error {
                print("websocket encountered an error: (e.localizedDescription)")
            } else {
                print("websocket encountered an error")
            }
        }
        
        // MARK: Write Text Action
        
        @objc func writeText(_ sender: UIButton) {
            socket.write(string: "hello there!")
        }
        
        // MARK: Disconnect Action
        
        @objc func disconnect(_ sender: UIButton) {
            if isConnected {
                sender.setTitle("Connect", for: .normal)
                socket.disconnect()
            } else {
                sender.setTitle("Disconnect", for: .normal)
                socket.connect()
            }
        }
    
    
    }

    分享链接:

    工作之余,开了一个淘宝小店,分别销售日常必备生活用品,期待您的光临!点击下图,跳转店铺首页!
  • 相关阅读:
    ReentrantLock与synchronized的差别
    读TIJ -1 对象入门
    wikioi 2573 大顶堆与小顶堆并用
    开源 免费 java CMS
    UVA10972
    springboot5
    spring-boot4
    spring-boot3
    spring-boot2
    spring-boot1
  • 原文地址:https://www.cnblogs.com/xjf125/p/14691276.html
Copyright © 2011-2022 走看看