-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebsocketClient.jl
189 lines (177 loc) · 5.7 KB
/
WebsocketClient.jl
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""
WebsocketClient([; options...])
Constructs a new WebsocketClient, overriding [`clientConfig`](@ref) with the passed options.
# Example
```julia
using SimpleWebsockets
client = WebsocketClient([; options...])
```
"""
struct WebsocketClient
config::NamedTuple
callbacks::Dict{Symbol, Union{Bool, Function}}
flags::Dict{Symbol, Bool}
function WebsocketClient(; config...)
@debug "WebsocketClient"
config = merge(clientConfig, (; config...))
config = merge(config, (; maskOutgoingPackets = true, type = "client") )
self = new(
config,
Dict{Symbol, Union{Bool, Function}}(
:connect => false,
:connectError => false,
),
Dict{Symbol, Bool}(
:isopen => false
)
)
end
end
"""
listen(callback::Function, client::SimpleWebsockets.WebsocketClient, event::Symbol)
Register event callbacks onto a client. The callback must be a function with exactly one argument.
Valid events are:
- :connect
- :connectError
# Example
```julia
listen(client, :connect) do ws
#...
end
```
"""
function listen(
cb::Function,
self::WebsocketClient,
key::Symbol
)
if !haskey(self.callbacks, key)
return @warn "WebsocketClient has no listener for :$key."
end
if haskey(self.callbacks, key) && !(self.callbacks[key] isa Function)
self.callbacks[key] = data -> (
@async try
cb(data)
catch err
err = CallbackError(err, catch_backtrace())
err.log()
exit()
end
)
end
end
function makeConnection(
self::WebsocketClient,
urlString::String,
headers::Dict{String, String};
options...
)
@debug "WebsocketClient.connect"
if isopen(self)
@warn """called "connect" on a WebsocketClient that is open or opening."""
return
end
options = merge((; options...), clientOptions)
connected = Condition()
self.flags[:isopen] = true
@async try
connection = wait(connected)
if self.callbacks[:connect] isa Function
self.callbacks[:connect](connection)
wait(connection.closed)
self.flags[:isopen] = false
else
throw(error("""called "open" before registering ":connect" event."""))
end
catch err
err = ConnectError(err, catch_backtrace())
self.flags[:isopen] = false
if self.callbacks[:connectError] isa Function
self.callbacks[:connectError](err)
else
err.log()
exit()
end
end
try
headers = makeHeaders(headers)
if !(headers["Sec-WebSocket-Version"] in ["8", "13"])
throw(error("only version 8 and 13 of websocket protocol supported."))
end
if haskey(headers, "Sec-WebSocket-Extensions")
throw(error("websocket extensions not supported in client"))
end
connect(
self.config,
urlString,
connected,
headers;
options...
)
catch err
@async notify(connected, err; error = true)
end
end
function validateHandshake(headers::Dict{String, String}, request::HTTP.Messages.Response)
if request.status != 101
throw(error("connection error with status: $(request.status)"))
end
if !HTTP.hasheader(request, "Connection", "Upgrade")
throw(error("""did not receive "Connection: Upgrade" """))
end
if !HTTP.hasheader(request, "Upgrade", "websocket")
throw(error("""did not receive "Upgrade: websocket" """))
end
if !HTTP.hasheader(request, "Sec-WebSocket-Accept", acceptHash(headers["Sec-WebSocket-Key"]))
throw(error("""invalid "Sec-WebSocket-Accept" response from server"""))
end
if HTTP.hasheader(request, "Sec-WebSocket-Extensions")
@warn "Server uses websocket extensions" (;
value = HTTP.header(request, "Sec-WebSocket-Extensions"),
caution = "Websocket extensions are not supported in the client and may cause connection closure."
)...
end
end
function connect(
config::NamedTuple,
url::String,
connected::Condition,
headers::Dict{String, String};
options...
)
@debug "WebsocketClient.connect"
let self
HTTP.open("GET", url, headers;
options...
) do io
tcp = io.stream.io isa TCPSocket ? io.stream.io : io.stream.io.bio
VERSION >= v"1.3" && Sockets.nagle(tcp, config.useNagleAlgorithm) #Sockets.nagle needs Julia >= 1.3
try
request = startread(io)
validateHandshake(headers, request)
self = WebsocketConnection(io.stream, config)
notify(connected, self)
catch err
notify(connected, err; error = true)
return
end
startConnection(self, io)
end
end
end
"""
open(client::WebsocketClient, url::String [, headers::Dict{String, String}; options...])
Open a new websocket client connection at the given `url`. Blocks until the connection is closed.
Optionally provide custom `headers` for the http request.
`; options...` are passed to the underlying [HTTP.request](https://juliaweb.github.io/HTTP.jl/v1.0.2/reference/#Client-Requests)
"""
function Base.open(client::WebsocketClient, url::String, headers::Dict{String, String} = Dict{String, String}(); options...)
makeConnection(client, url, headers; options...)
end
"""
isopen(client::WebsocketClient)::Bool
Returns a Bool indication if the client TCP connection is open.
"""
function Base.isopen(client::WebsocketClient)
client.flags[:isopen]
end