Is it safe to modify buffer after WebSocket.send()?

197 views Asked by At

Does WebSocket.send() copy the passed array buffer so that it is safe to modify it afterward? Say:

var a = new Uint8Array([1, 2, 3]);
websocket.send(a);
a[2] = 4;

Is this safe even if the socket is full and the buffer isn't sent immediately?

1

There are 1 answers

0
jfriend00 On BEST ANSWER

Yes, it is safe to modify your buffer after WebSocket.send().

The working draft of the WebSocket specification refers to a separate buffer for the socket so the data is either immediately sent or copied into a separate buffer.

The send(data) method transmits data using the connection. If the readyState attribute is CONNECTING, it must raise an INVALID_STATE_ERR exception. If the data argument has any unpaired surrogates, then it must raise SYNTAX_ERR. If the connection is established, and the string has no unpaired surrogates, then the user agent must send data using the Web Socket. If the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must close the Web Socket connection. The method must then return true if the connection is still established (and the data was queued or sent successfully), or false if the connection is closed (e.g. because the user agent just had a buffer overflow and failed to send the data).

Note, that if the socket buffer is full, then that triggers an error condition and the socket is closed.

In addition, this makes sense from an implementation point of view. Exactly when the bytes are actually sent over the network is a detail of the socket implementation and thus, they have to copy the bytes into their own buffer in order to maintain control over the data before it is sent (a safe programming practice for a design like this). Otherwise, there could be horrible timing issues with resue of the buffer by the calling code.