O2WebsocketManager.swift 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // O2WebsocketManager.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2020/6/1.
  6. // Copyright © 2020 zoneland. All rights reserved.
  7. //
  8. import Foundation
  9. import Starscream
  10. import CocoaLumberjack
  11. class O2WebsocketManager {
  12. static let instance: O2WebsocketManager = {
  13. return O2WebsocketManager()
  14. }()
  15. private init() { }
  16. private var socket: WebSocket?
  17. // wsUrl: ws://xxx.o2oa.net:20020/x_message_assemble_communicate/ws/collaboration?x-token=xxxxxxx
  18. //开启连接
  19. func startConnect(wsUrl: String, delegate: WebSocketDelegate) {
  20. let request = URLRequest(url: URL(string: wsUrl)!)
  21. socket = WebSocket(request: request)
  22. socket?.delegate = delegate
  23. socket?.connect()
  24. }
  25. //发送消息
  26. func send(msg: String) {
  27. guard let s = socket else {
  28. DDLogError("socket 为空 还未启动 无法发送消息")
  29. return
  30. }
  31. s.write(string: msg)
  32. }
  33. //关闭连接
  34. func closeConnect() {
  35. guard let s = socket else {
  36. DDLogError("socket 为空 无需关闭")
  37. return
  38. }
  39. s.disconnect(closeCode: CloseCode.goingAway.rawValue)
  40. socket = nil
  41. }
  42. }