MCPcopy Index your code
hub / github.com/python-websockets/websockets / serialize

Method serialize

src/websockets/frames.py:274–332  ·  view source on GitHub ↗

Serialize a WebSocket frame. Args: mask: Whether the frame should be masked i.e. whether the write happens on the client side. extensions: List of extensions, applied in order. Raises: ProtocolError: If the frame contains

(
        self,
        *,
        mask: bool,
        extensions: Sequence[extensions.Extension] | None = None,
    )

Source from the content-addressed store, hash-verified

272 return frame
273
274 def serialize(
275 self,
276 *,
277 mask: bool,
278 extensions: Sequence[extensions.Extension] | None = None,
279 ) -> bytes:
280 """
281 Serialize a WebSocket frame.
282
283 Args:
284 mask: Whether the frame should be masked i.e. whether the write
285 happens on the client side.
286 extensions: List of extensions, applied in order.
287
288 Raises:
289 ProtocolError: If the frame contains incorrect values.
290
291 """
292 self.check()
293
294 if extensions is None:
295 extensions = []
296 for extension in extensions:
297 self = extension.encode(self)
298
299 output = io.BytesIO()
300
301 # Prepare the header.
302 head1 = (
303 (0b10000000 if self.fin else 0)
304 | (0b01000000 if self.rsv1 else 0)
305 | (0b00100000 if self.rsv2 else 0)
306 | (0b00010000 if self.rsv3 else 0)
307 | self.opcode
308 )
309
310 head2 = 0b10000000 if mask else 0
311
312 length = len(self.data)
313 if length < 126:
314 output.write(struct.pack("!BB", head1, head2 | length))
315 elif length < 65536:
316 output.write(struct.pack("!BBH", head1, head2 | 126, length))
317 else:
318 output.write(struct.pack("!BBQ", head1, head2 | 127, length))
319
320 if mask:
321 mask_bytes = secrets.token_bytes(4)
322 output.write(mask_bytes)
323
324 # Prepare the data.
325 data: BytesLike
326 if mask:
327 data = apply_mask(self.data, mask_bytes)
328 else:
329 data = self.data
330 output.write(data)
331

Callers 15

send_requestMethod · 0.45
send_responseMethod · 0.45
send_frameMethod · 0.45
writeMethod · 0.45
serialize_closeFunction · 0.45
write_close_frameMethod · 0.45
assertFrameDataMethod · 0.45
assertCloseDataMethod · 0.45
test_serialize_errorsMethod · 0.45
test_serializeMethod · 0.45
test_serializeMethod · 0.45

Calls 4

checkMethod · 0.95
apply_maskFunction · 0.85
encodeMethod · 0.45
writeMethod · 0.45

Tested by 15

assertFrameDataMethod · 0.36
assertCloseDataMethod · 0.36
test_serialize_errorsMethod · 0.36
test_serializeMethod · 0.36
test_serializeMethod · 0.36
close_connectionMethod · 0.36