Skip to content

Commit 1d16ae6

Browse files
committed
Added example of collecting binary data
1 parent f040762 commit 1d16ae6

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

README.md

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,32 @@ Emitted in case of error (like trying to send text data while still sending bina
149149
Emitted when a text is received. `str` is a string
150150

151151
## Event: 'binary(inStream)'
152-
Emitted when the beginning of binary data is received. `inStream` is a ReadableStream
152+
Emitted when the beginning of binary data is received. `inStream` is a [ReadableStream](https://nodejs.org/api/stream.html#stream_class_stream_readable):
153+
```javascript
154+
var server = ws.createServer(function (conn) {
155+
console.log("New connection")
156+
conn.on("binary", function (inStream) {
157+
// Empty buffer for collecting binary data
158+
var data = new Buffer(0)
159+
// Read chunks of binary data and add to the buffer
160+
inStream.on("readable", function () {
161+
var newData = inStream.read()
162+
if (newData)
163+
data = Buffer.concat([data, newData], data.length+newData.length)
164+
})
165+
inStream.on("end", function () {
166+
console.log("Received " + data.length + " bytes of binary data")
167+
process_my_data(data)
168+
})
169+
})
170+
conn.on("close", function (code, reason) {
171+
console.log("Connection closed")
172+
})
173+
}).listen(8001)
174+
```
153175

154176
## Event: 'connect()'
155177
Emitted when the connection is fully established (after the handshake)
156178

157179
## Event: 'pong(data)'
158-
Emitted when a [pong](http://tools.ietf.org/html/rfc6455#section-5.5.3) is received, usually after a ping was sent. `data` is the pong payload, as a string
180+
Emitted when a [pong](http://tools.ietf.org/html/rfc6455#section-5.5.3) is received, usually after a ping was sent. `data` is the pong payload, as a string

0 commit comments

Comments
 (0)