Construct a WebSocket frame.
 @example
   frame = LibWebSocket::Frame.new('foo')
   frame.to_s # => \x00foo\xff
6271
def to_s
      ary = ["\x00", @buffer.dup, "\xff"]

      ary.collect{ |s| s.force_encoding('UTF-8') if s.respond_to?(:force_encoding) }

      return ary.join
    end
796534
private static ByteBuf createSettingsFrame(ChannelHandlerContext ctx, ByteBuf payload) {
        ByteBuf frame = ctx.alloc().buffer(FRAME_HEADER_LENGTH + payload.readableBytes());
        writeFrameHeader(frame, payload.readableBytes(), SETTINGS, new Http2Flags(), 0);
        frame.writeBytes(payload);
        payload.release();
        return frame;
    }
525216
def append(event, frame, arg)
      item = EventStruct.new(event, arg, frame)
      @pos = self.succ_pos
      @marks.shift if @marks[0] == @pos
      @buf[@pos] = item
      @size     += 1 unless @maxsize && @size == @maxsize
    end
1288476
async def _send_frame(self, message: bytes, opcode: int,
                          compress: Optional[int]=None) -> None:
        """"""
        if self._closing:
            ws_logger.warning('websocket connection is closing.')

        rsv = 0

        # Only compress larger packets (disabled)
        # Does small packet needs to be compressed?
        # if self.compress and opcode < 8 and len(message) > 124:
        if (compress or self.compress) and opcode < 8:
            if compress:
                # Do not set self._compress if compressing is for this frame
                compressobj = zlib.compressobj(wbits=-compress)
            else:  # self.compress
                if not self._compressobj:
                    self._compressobj = zlib.compressobj(wbits=-self.compress)
                compressobj = self._compressobj

            message = compressobj.compress(message)
            message = message + compressobj.flush(
                zlib.Z_FULL_FLUSH if self.notakeover else zlib.Z_SYNC_FLUSH)
            if message.endswith(_WS_DEFLATE_TRAILING):
                message = message[:-4]
            rsv = rsv | 0x40

        msg_length = len(message)

        use_mask = self.use_mask
        if use_mask:
            mask_bit = 0x80
        else:
            mask_bit = 0

        if msg_length < 126:
            header = PACK_LEN1(0x80 | rsv | opcode, msg_length | mask_bit)
        elif msg_length < (1 << 16):
            header = PACK_LEN2(0x80 | rsv | opcode, 126 | mask_bit, msg_length)
        else:
            header = PACK_LEN3(0x80 | rsv | opcode, 127 | mask_bit, msg_length)
        if use_mask:
            mask = self.randrange(0, 0xffffffff)
            mask = mask.to_bytes(4, 'big')
            message = bytearray(message)
            _websocket_mask(mask, message)
            self.transport.write(header + mask + message)
            self._output_size += len(header) + len(mask) + len(message)
        else:
            if len(message) > MSG_SIZE:
                self.transport.write(header)
                self.transport.write(message)
            else:
                self.transport.write(header + message)

            self._output_size += len(header) + len(message)

        if self._output_size > self._limit:
            self._output_size = 0
            await self.protocol._drain_helper()
271620
async def create_websocket_server(sock, filter=None):  # pylint: disable=W0622
    
    ws = Websocket()
    await ws.start_server(sock, filter=filter)
    return ws
1056981
def construct_hash
      vars = instance_variables.reject { |x| [:@client, :@original].include? x }
      Hash[vars.map { |key| [key.to_s[1..key.length], instance_variable_get(key)] }]
    end
883128
def parse_frame(buf):
    """"""
    # read header
    while buf.available < 2:
        yield

    data = buf.read(2)
    first_byte, second_byte = struct.unpack('!BB', data)

    fin = (first_byte >> 7) & 1
    rsv1 = (first_byte >> 6) & 1
    rsv2 = (first_byte >> 5) & 1
    rsv3 = (first_byte >> 4) & 1
    opcode = first_byte & 0xf

    # frame-fin = %x0 ; more frames of this message follow
    #           / %x1 ; final frame of this message
    # frame-rsv1 = %x0 ; 1 bit, MUST be 0 unless negotiated otherwise
    # frame-rsv2 = %x0 ; 1 bit, MUST be 0 unless negotiated otherwise
    # frame-rsv3 = %x0 ; 1 bit, MUST be 0 unless negotiated otherwise
    if rsv1 or rsv2 or rsv3:
        raise WebSocketError('Received frame with non-zero reserved bits')

    if opcode > 0x7 and fin == 0:
        raise WebSocketError('Received fragmented control frame')

    if fin == 0 and opcode == OPCODE_CONTINUATION:
        raise WebSocketError(
            'Received new fragment frame with non-zero opcode')

    has_mask = (second_byte >> 7) & 1
    length = (second_byte) & 0x7f

    # Control frames MUST have a payload length of 125 bytes or less
    if opcode > 0x7 and length > 125:
        raise WebSocketError(
            "Control frame payload cannot be larger than 125 bytes")

    # read payload
    if length == 126:
        while buf.available < 2:
            yield

        length = struct.unpack_from('!H', buf.read(2))[0]
    elif length > 126:
        while buf.available < 4:
            yield

        length = struct.unpack_from('!Q', buf.read(4))[0]

    if has_mask:
        while buf.available < 4:
            yield

        mask = buf.read(4)

    if length:
        while buf.available < length:
            yield

        payload = buf.read(length)
    else:
        payload = b''

    if has_mask:
        mask = [ord(i) for i in mask]
        payload = [chr(ord(b) ^ mask[i % 4]) for i, b in enumerate(payload)]

    yield fin, opcode, payload
778376
def _parseAtFrame(self, src):
        
        src = src[len('@frame '):].lstrip()
        box, src = self._getIdent(src)
        src, properties = self._parseDeclarationGroup(src.lstrip())
        result = [self.cssBuilder.atFrame(box, properties)]
        return src.lstrip(), result
87863
function xframeFactory(options) {
  options = options || {};

  var str = 'DENY';
  if (isString(options)) {
    str = options;
  } else {
    if (options.sameOrigin) {
      str = 'SAMEORIGIN';
    }
    if (options.allow) {
      if (options.sameOrigin) {
        throw new Error('Cannot specify both ALLOW-FROM and SAMEORIGIN');
      }

      str = 'ALLOW-FROM ' + options.allow;
    }
  }

  return function xframe(req, res, next) {
    res.setHeader(HEADER, str);
    next();
  };
}
670851
function EmulatedWebSocketServerFactory() {
        this.createServer = function (connectCallback) {
            var server = {
                _connect: function (socket) {
                    var conn = {
                        _client: socket,
                        _listeners: { "text": [], "close": [] },
                        on: function (type, listener) {
                            conn._listeners[type].push(listener);
                        },
                        _fire: function (type, args) {
                            conn._listeners[type].forEach(function (listener) {
                                listener.apply(null, args);
                            });
                        },

                        _text: function (msg) {
                            conn._fire("text", [msg]);
                        },
                        sendText: function (msg) {
                            setTimeout(function () {
                                conn._client._text(msg);
                            }, 0);
                        },
                        close: function (code, reason) {
                            setTimeout(function () {
                                conn._client._disconnect(code, reason);
                            }, 0);
                        },
                        _disconnect: function (code, reason) {
                            conn._fire("close", [code, reason]);
                        }
                    };
                    connectCallback(conn);
                    return conn;
                },
                listen: function (port) {
                    EmulatedWebSocketServerFactory.listeners[port] = this;
                    return this;
                }
            }
            return server;
        }
    }
198488
def build_socket(self):
        
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(self.SOCKET_TIMEOUT)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # Check if TLS
            if self.request_object.protocol == 'https':
                self.sock = ssl.wrap_socket(self.sock, ciphers=self.CIPHERS)
            self.sock.connect(
                (self.request_object.dest_addr, self.request_object.port))
        except socket.error as msg:
            raise errors.TestError(
                'Failed to connect to server',
                {
                    'host': self.request_object.dest_addr,
                    'port': self.request_object.port,
                    'proto': self.request_object.protocol,
                    'message': msg,
                    'function': 'http.HttpUA.build_socket'
                })
521466
function (url) {
            var self = this;
            this._ws = new WebSocket(url);

            // One potential source of confusion: the transport sends two "types" of messages -
            // these are distinct from the protocol's own messages. This is because this transport
            // needs to send an initial "connect" message telling the Brackets side of the transport
            // the URL of the page that it's connecting from, distinct from the actual protocol
            // message traffic. Actual protocol messages are sent as a JSON payload in a message of
            // type "message".
            //
            // Other transports might not need to do this - for example, a transport that simply
            // talks to an iframe within the same process already knows what URL that iframe is
            // pointing to, so the only comunication that needs to happen via postMessage() is the
            // actual protocol message strings, and no extra wrapping is necessary.

            this._ws.onopen = function (event) {
                // Send the initial "connect" message to tell the other end what URL we're from.
                self._ws.send(JSON.stringify({
                    type: "connect",
                    url: global.location.href
                }));
                console.log("[Brackets LiveDev] Connected to Brackets at " + url);
                if (self._callbacks && self._callbacks.connect) {
                    self._callbacks.connect();
                }
            };
            this._ws.onmessage = function (event) {
                console.log("[Brackets LiveDev] Got message: " + event.data);
                if (self._callbacks && self._callbacks.message) {
                    self._callbacks.message(event.data);
                }
            };
            this._ws.onclose = function (event) {
                self._ws = null;
                if (self._callbacks && self._callbacks.close) {
                    self._callbacks.close();
                }
            };
            // TODO: onerror
        }
305881
def add_frame(frame)
      raise ArgumentError, "Invalid argument 'frame'. Expected Frame, got #{frame.class}." unless frame.is_a?(Frame)
      # Do not add it again if the frame already belongs to this instance:
      @frames << frame unless @associated_frames[frame.uid]
      @associated_frames[frame.uid] = frame
    end
393263
def _get_framed(self, buf, offset, insert_payload):
    
    header_offset = offset + self._header_len
    self.length = insert_payload(buf, header_offset, self.payload)
    struct.pack_into(self._header_fmt,
                     buf,
                     offset,
                     self.preamble,
                     self.msg_type,
                     self.sender,
                     self.length)
    crc_offset = header_offset + self.length
    preamble_bytes = 1
    crc_over_len = self._header_len + self.length - preamble_bytes
    self.crc = crc16jit(buf, offset+1, 0, crc_over_len)
    struct.pack_into(self._crc_fmt, buf, crc_offset, self.crc)
    length = preamble_bytes + crc_over_len + self._crc_len
    return length
197744
def encode(frame)
      frames = if frame[:type] == :headers || frame[:type] == :push_promise
        encode_headers(frame) # HEADERS and PUSH_PROMISE may create more than one frame
      else
        [frame]               # otherwise one frame
      end

      frames.map { |f| @framer.generate(f) }
    end
479270
function createChannel(url) {
  var parsed = URL.parse(url)

  if (parsed.protocol == "ws:")  return fromWebSocketURL(url)
  if (parsed.protocol == "wss:") return fromWebSocketURL(url)

  throw new Error("unhandleable url")
}
717142
def build_frame(cache, keys)
      line, type = keys
      abs_path, lineno, function, _module_name = parse_line(line)

      frame = Stacktrace::Frame.new
      frame.abs_path = abs_path
      frame.filename = strip_load_path(abs_path)
      frame.function = function
      frame.lineno = lineno.to_i
      frame.library_frame = library_frame?(config, abs_path)

      line_count =
        context_lines_for(config, type, library_frame: frame.library_frame)
      frame.build_context line_count

      cache[[line, type]] = frame
    end