KMWebsocket.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // KMWebsocket.swift
  3. // PDF Reader Pro DMG
  4. //
  5. // Created by wanjun on 2023/6/29.
  6. //
  7. import Cocoa
  8. import Starscream
  9. @objc protocol KMWebsocketDelegate {
  10. func websocketDidConnect()
  11. func websocketDidDisconnect()
  12. func websocketDidError(error: Error)
  13. func websocketDidReceive(content: String)
  14. func webSocketDidReceiveData(data: Data)
  15. }
  16. class KMWebsocket: NSObject {
  17. @objc weak var delegate: KMWebsocketDelegate?
  18. var newSocket: WebSocket!
  19. var isConnectedState = false
  20. @objc func connect(endPoint: String) {
  21. var request = URLRequest(url: URL(string: endPoint as String)!)
  22. request.timeoutInterval = 5
  23. newSocket = WebSocket(request: request)
  24. newSocket!.delegate = self
  25. newSocket!.connect()
  26. }
  27. func handleError(_ error: Error?) {
  28. if let e = error as? WSError {
  29. print("websocket encountered an error: \(e.message)")
  30. } else if let e = error {
  31. print("websocket encountered an error: \(e.localizedDescription)")
  32. } else {
  33. print("websocket encountered an error")
  34. }
  35. }
  36. @objc func disconnect() {
  37. newSocket?.disconnect()
  38. }
  39. @objc func isConnected()->Bool {
  40. return isConnectedState
  41. }
  42. }
  43. extension KMWebsocket: WebSocketDelegate {
  44. func didReceive(event: Starscream.WebSocketEvent, client: Starscream.WebSocketClient) {
  45. switch event {
  46. case .connected(let headers):
  47. isConnectedState = true
  48. self.delegate?.websocketDidConnect()
  49. case .disconnected(let reason, let code):
  50. isConnectedState = false
  51. self.delegate?.websocketDidDisconnect()
  52. case .text(let string):
  53. print("newSocket text=" + string)
  54. self.delegate?.websocketDidReceive(content: string)
  55. case .binary(let data):
  56. self.delegate?.webSocketDidReceiveData(data: data)
  57. case .ping(_):
  58. break
  59. case .pong(_):
  60. break
  61. case .viabilityChanged(_):
  62. break
  63. case .reconnectSuggested(_):
  64. break
  65. case .cancelled:
  66. isConnectedState = false
  67. case .error(let error):
  68. isConnectedState = false
  69. handleError(error)
  70. @unknown default:
  71. print(event)
  72. }
  73. }
  74. }