-
-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathWebSocketClient.swift
162 lines (147 loc) · 5.92 KB
/
WebSocketClient.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import Foundation
import NIO
import NIOConcurrencyHelpers
import NIOHTTP1
import NIOWebSocket
import NIOSSL
public final class WebSocketClient {
public enum Error: Swift.Error, LocalizedError {
case invalidURL
case invalidResponseStatus(HTTPResponseHead)
case alreadyShutdown
public var errorDescription: String? {
return "\(self)"
}
}
public enum EventLoopGroupProvider {
case shared(EventLoopGroup)
case createNew
}
public struct Configuration {
public var tlsConfiguration: TLSConfiguration?
public var inboundMaxFrameSize: WebSocketMaxFrameSize
public var outboundMaxFrameSize: WebSocketMaxFrameSize
public init(
tlsConfiguration: TLSConfiguration? = nil,
maxFrameSize: WebSocketMaxFrameSize = WebSocketMaxFrameSize.default
) {
self.tlsConfiguration = tlsConfiguration
self.inboundMaxFrameSize = maxFrameSize
self.outboundMaxFrameSize = maxFrameSize
}
public init(
tlsConfiguration: TLSConfiguration? = nil,
inboundMaxFrameSize: WebSocketMaxFrameSize = WebSocketMaxFrameSize.default,
outboundMaxFrameSize: WebSocketMaxFrameSize = WebSocketMaxFrameSize.default
) {
self.tlsConfiguration = tlsConfiguration
self.inboundMaxFrameSize = inboundMaxFrameSize
self.outboundMaxFrameSize = outboundMaxFrameSize
}
}
let eventLoopGroupProvider: EventLoopGroupProvider
let group: EventLoopGroup
let configuration: Configuration
let isShutdown = NIOAtomic.makeAtomic(value: false)
public init(eventLoopGroupProvider: EventLoopGroupProvider, configuration: Configuration = .init()) {
self.eventLoopGroupProvider = eventLoopGroupProvider
switch self.eventLoopGroupProvider {
case .shared(let group):
self.group = group
case .createNew:
self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
}
self.configuration = configuration
}
public func connect(
scheme: String,
host: String,
port: Int,
path: String = "/",
headers: HTTPHeaders = [:],
onUpgrade: @escaping (WebSocket) -> ()
) -> EventLoopFuture<Void> {
assert(["ws", "wss"].contains(scheme))
let upgradePromise = self.group.next().makePromise(of: Void.self)
let bootstrap = ClientBootstrap(group: self.group)
.channelOption(ChannelOptions.socket(SocketOptionLevel(IPPROTO_TCP), TCP_NODELAY), value: 1)
.channelInitializer { channel in
let httpHandler = HTTPInitialRequestHandler(
host: host,
path: path,
headers: headers,
upgradePromise: upgradePromise
)
var key: [UInt8] = []
for _ in 0..<16 {
key.append(.random(in: .min ..< .max))
}
let websocketUpgrader = NIOWebSocketClientUpgrader(
requestKey: Data(key).base64EncodedString(),
maxFrameSize: self.configuration.inboundMaxFrameSize.value,
automaticErrorHandling: true,
upgradePipelineHandler: { channel, req in
return WebSocket.client(
on: channel,
outboundMaxFrameSize: self.configuration.outboundMaxFrameSize,
onUpgrade: onUpgrade
)
}
)
let config: NIOHTTPClientUpgradeConfiguration = (
upgraders: [websocketUpgrader],
completionHandler: { context in
upgradePromise.succeed(())
channel.pipeline.removeHandler(httpHandler, promise: nil)
}
)
if scheme == "wss" {
do {
let context = try NIOSSLContext(
configuration: self.configuration.tlsConfiguration ?? .forClient()
)
let tlsHandler = try NIOSSLClientHandler(context: context, serverHostname: host)
return channel.pipeline.addHandler(tlsHandler).flatMap {
channel.pipeline.addHTTPClientHandlers(leftOverBytesStrategy: .forwardBytes, withClientUpgrade: config)
}.flatMap {
channel.pipeline.addHandler(httpHandler)
}
} catch {
return channel.pipeline.close(mode: .all)
}
} else {
return channel.pipeline.addHTTPClientHandlers(
leftOverBytesStrategy: .forwardBytes,
withClientUpgrade: config
).flatMap {
channel.pipeline.addHandler(httpHandler)
}
}
}
let connect = bootstrap.connect(host: host, port: port)
connect.cascadeFailure(to: upgradePromise)
return connect.flatMap { channel in
return upgradePromise.futureResult
}
}
public func syncShutdown() throws {
switch self.eventLoopGroupProvider {
case .shared:
return
case .createNew:
if self.isShutdown.compareAndExchange(expected: false, desired: true) {
try self.group.syncShutdownGracefully()
} else {
throw WebSocketClient.Error.alreadyShutdown
}
}
}
deinit {
switch self.eventLoopGroupProvider {
case .shared:
return
case .createNew:
assert(self.isShutdown.load(), "WebSocketClient not shutdown before deinit.")
}
}
}