WebSocket
or
There and Back Again
Artem Trubachev, 2018
Problem?
HTTP
Comet
- polling
- long polling
- endless iframe
- other kludges
Comet
WebSocket — is a communications protocol, providing full-duplex communication channels over a single TCP connection.
There
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
Back
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
There and Back
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
There and Back
Control frames
- Close
- Ping
- Pong
There and Back
Data frames
- Text
- Binary
There and Back
Reserved frames
Security
- Origin header
- no auth
wss
Extensions
Sec-WebSocket-Extensions: bar; baz=2
Sec-WebSocket-Protocol: soap, wamp
Here
var socket = new WebSocket("ws://localhost");
socket.onopen = function() {
console.log("Connection established");
};
socket.onclose = function(event) {
console.log("Connection closed");
};
socket.onmessage = function(event) {
console.log("Data received: " + event.data);
};
There
EM.run {
EM::WebSocket.run(:host => "localhost", :port => 80) do |ws|
ws.onopen { |handshake|
ws.send "Hello Client, you connected to #{handshake.path}"
}
ws.onclose { |msg|
puts 'Connection closed'
}
ws.onmessage { |msg|
ws.send "Pong: #{msg}"
}
end
}
Support
10
11
11
16
6
12.10
4.4
Debigging
Performance
1000 clients
10 000 clients
100 000 clients
1 req/sec
Performance
4ghz i7 4790Ks 16GB of RAM
Performance
4ghz i7 4790Ks 16GB of RAM
Cons
- resources
- no cache
- connection breaks
- separate process
Pros
- full duplex
- less traffic
- less delay
- not only browser
- easy to use
- standard
- one connection
Usage
- Chats
- Online games
- Collaborate editing
- Monitoring
- Your startup
Summary
- good support
- standard
- performance boost
- less traffic
- not a silver bullet
Thanks
trubachev.artem@gmail.com
WebSocket or There and Back Again
By Artem Trubachev
WebSocket or There and Back Again
- 623