WebSocketPeer

继承: PacketPeer < RefCounted < Object

A WebSocket connection.

描述

This class represents WebSocket connection, and can be used as a WebSocket client (RFC 6455-compliant) or as a remote peer of a WebSocket server.

You can send WebSocket binary frames using PacketPeer.put_packet, and WebSocket text frames using send (prefer text frames when interacting with text-based API). You can check the frame type of the last packet via was_string_packet.

To start a WebSocket client, first call connect_to_url, then regularly call poll (e.g. during Node process). You can query the socket state via get_ready_state, get the number of pending packets using PacketPeer.get_available_packet_count, and retrieve them via PacketPeer.get_packet.


    extends Node
    
    var socket = WebSocketPeer.new()
    
    func _ready():
        socket.connect_to_url("wss://example.com")
    
    func _process(delta):
        socket.poll()
        var state = socket.get_ready_state()
        if state == WebSocketPeer.STATE_OPEN:
            while socket.get_available_packet_count():
                print("Packet: ", socket.get_packet())
        elif state == WebSocketPeer.STATE_CLOSING:
            # Keep polling to achieve proper close.
            pass
        elif state == WebSocketPeer.STATE_CLOSED:
            var code = socket.get_close_code()
            var reason = socket.get_close_reason()
            print("WebSocket closed with code: %d, reason %s. Clean: %s" % [code, reason, code != -1])
            set_process(false) # Stop processing.

To use the peer as part of a WebSocket server refer to accept_stream and the online tutorial.

属性

方法

Erroraccept_stream ( stream: StreamPeer )
voidclose ( code: int = 1000, reason: String = "" )
Errorconnect_to_url ( url: String, tls_client_options: TLSOptions = null )
intget_close_code ( ) const1
Stringget_close_reason ( ) const1
Stringget_connected_host ( ) const1
intget_connected_port ( ) const1
intget_current_outbound_buffered_amount ( ) const1
Stateget_ready_state ( ) const1
Stringget_requested_url ( ) const1
Stringget_selected_protocol ( ) const1
voidpoll ( )
Errorsend ( message: PackedByteArray, write_mode: WriteMode = 1 )
Errorsend_text ( message: String )
voidset_no_delay ( enabled: bool )
boolwas_string_packet ( ) const1

枚举

enum WriteMode:

WriteMode WRITE_MODE_TEXT = 0

Specifies that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed).

WriteMode WRITE_MODE_BINARY = 1

Specifies that WebSockets messages should be transferred as binary payload (any byte combination is allowed).


enum State:

State STATE_CONNECTING = 0

Socket has been created. The connection is not yet open.

State STATE_OPEN = 1

The connection is open and ready to communicate.

State STATE_CLOSING = 2

The connection is in the process of closing. This means a close request has been sent to the remote peer but confirmation has not been received.

State STATE_CLOSED = 3

The connection is closed or couldn't be opened.


属性说明

PackedStringArray handshake_headers = PackedStringArray()

The extra HTTP headers to be sent during the WebSocket handshake.

Note: Not supported in Web exports due to browsers' restrictions.

Note: The returned array is copied and any changes to it will not update the original property value. See PackedStringArray for more details.


int inbound_buffer_size = 65535

  • void set_inbound_buffer_size ( value: int )
  • int get_inbound_buffer_size ( )

The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the inbound packets).


int max_queued_packets = 2048

  • void set_max_queued_packets ( value: int )
  • int get_max_queued_packets ( )

The maximum amount of packets that will be allowed in the queues (both inbound and outbound).


int outbound_buffer_size = 65535

  • void set_outbound_buffer_size ( value: int )
  • int get_outbound_buffer_size ( )

The size of the input buffer in bytes (roughly the maximum amount of memory that will be allocated for the outbound packets).


PackedStringArray supported_protocols = PackedStringArray()

The WebSocket sub-protocols allowed during the WebSocket handshake.

Note: The returned array is copied and any changes to it will not update the original property value. See PackedStringArray for more details.


方法说明

Error accept_stream ( stream: StreamPeer )

Accepts a peer connection performing the HTTP handshake as a WebSocket server. The stream must be a valid TCP stream retrieved via TCPServer.take_connection, or a TLS stream accepted via StreamPeerTLS.accept_stream.

Note: Not supported in Web exports due to browsers' restrictions.


void close ( code: int = 1000, reason: String = "" )

Closes this WebSocket connection. code is the status code for the closure (see RFC 6455 section 7.4 for a list of valid status codes). reason is the human readable reason for closing the connection (can be any UTF-8 string that's smaller than 123 bytes). If code is negative, the connection will be closed immediately without notifying the remote peer.

Note: To achieve a clean close, you will need to keep polling until STATE_CLOSED is reached.

Note: The Web export might not support all status codes. Please refer to browser-specific documentation for more details.


Error connect_to_url ( url: String, tls_client_options: TLSOptions = null )

Connects to the given URL. TLS certificates will be verified against the hostname when connecting using the wss:// protocol. You can pass the optional tls_client_options parameter to customize the trusted certification authorities, or disable the common name verification. See TLSOptions.client and TLSOptions.client_unsafe.

Note: To avoid mixed content warnings or errors in Web, you may have to use a url that starts with wss:// (secure) instead of ws://. When doing so, make sure to use the fully qualified domain name that matches the one defined in the server's TLS certificate. Do not connect directly via the IP address for wss:// connections, as it won't match with the TLS certificate.


int get_close_code ( ) const1

Returns the received WebSocket close frame status code, or -1 when the connection was not cleanly closed. Only call this method when get_ready_state returns STATE_CLOSED.


String get_close_reason ( ) const1

Returns the received WebSocket close frame status reason string. Only call this method when get_ready_state returns STATE_CLOSED.


String get_connected_host ( ) const1

Returns the IP address of the connected peer.

Note: Not available in the Web export.


int get_connected_port ( ) const1

Returns the remote port of the connected peer.

Note: Not available in the Web export.


int get_current_outbound_buffered_amount ( ) const1

Returns the current amount of data in the outbound websocket buffer. Note: Web exports use WebSocket.bufferedAmount, while other platforms use an internal buffer.


State get_ready_state ( ) const1

Returns the ready state of the connection. See State.


String get_requested_url ( ) const1

Returns the URL requested by this peer. The URL is derived from the url passed to connect_to_url or from the HTTP headers when acting as server (i.e. when using accept_stream).


String get_selected_protocol ( ) const1

Returns the selected WebSocket sub-protocol for this connection or an empty string if the sub-protocol has not been selected yet.


void poll ( )

Updates the connection state and receive incoming packets. Call this function regularly to keep it in a clean state.


Error send ( message: PackedByteArray, write_mode: WriteMode = 1 )

Sends the given message using the desired write_mode. When sending a String, prefer using send_text.


Error send_text ( message: String )

Sends the given message using WebSocket text mode. Prefer this method over PacketPeer.put_packet when interacting with third-party text-based API (e.g. when using JSON formatted messages).


void set_no_delay ( enabled: bool )

Disable Nagle's algorithm on the underlying TCP socket (default). See StreamPeerTCP.set_no_delay for more information.

Note: Not available in the Web export.


bool was_string_packet ( ) const1

Returns true if the last received packet was sent as a text payload. See WriteMode.

2

本方法通常需要用户覆盖才能生效。

1

本方法无副作用,不会修改该实例的任何成员变量。

3

本方法除了能接受在此处描述的参数外,还能够继续接受任意数量的参数。

4

本方法用于构造某个类型。

5

调用本方法无需实例,可直接使用类名进行调用。

6

本方法描述的是使用本类型作为左操作数的有效运算符。

7

这个值是由下列位标志构成位掩码的整数。

8

无返回值。