【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, width: 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, width: 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() } } }