-
Notifications
You must be signed in to change notification settings - Fork 3
/
ACStarscreamWebSocket.swift
65 lines (54 loc) · 1.55 KB
/
ACStarscreamWebSocket.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// ACStarscreamWebSocket.swift
// ACActionCable
//
// Created by Julian Tigler on 9/15/20.
//
import Foundation
import ACActionCable
import Starscream
class ACStarscreamWebSocket: ACWebSocketProtocol {
var url: URL
var onConnected: ACConnectionHandler?
var onDisconnected: ACDisconnectionHandler?
var onText: ACTextHandler?
private var socket: WebSocket?
init(stringURL: String) {
url = URL(string: stringURL)!
}
func connect(headers: ACRequestHeaders?) {
guard socket == nil else { return }
socket = WebSocket(request: URLRequest(url: url))
socket?.delegate = self
socket?.request.allHTTPHeaderFields = headers
socket?.connect()
}
func disconnect() {
socket?.disconnect()
}
func send(text: String, completion: ACEventHandler?) {
socket?.write(string: text, completion: completion)
}
}
extension ACStarscreamWebSocket: WebSocketDelegate {
func didReceive(event: WebSocketEvent, client: WebSocket) {
switch event {
case .connected(let headers):
onConnected?(headers)
case .disconnected(let reason, _):
onSocketDisconnected(reason)
case .text(let text):
onText?(text)
case .cancelled:
onSocketDisconnected()
case .error(_):
onSocketDisconnected()
default:
break
}
}
private func onSocketDisconnected(_ reason: String? = nil) {
socket = nil
onDisconnected?(reason)
}
}