# web/websocketclient (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/web/websocketclient/

WebSocket communication handler. (a client that exchanges JSON)
- A port of the original web/websocketclient.js. Follows connect / disconnect / send(JSON) / is_connected / set_receive_event.
- The socket is ewebsock 0.8. Desktop uses a thread running tungstenite, the web (wasm) uses the browser WebSocket.
- In the original the browser calls onopen / onmessage / onclose. In the Rust version the scene calls tick every frame to take out the accumulated events.
  The read JSON is passed to receive_message as in the original. (the caller can also put it in directly)
  ```text
    // scene create
    self.web_socket_client.connect("ws://localhost:8080");
    // scene tick
    self.web_socket_client.tick();
    for message in self.web_socket_client.take_received_messages() { ... }
    self.web_socket_client.send(&serde_json::json!({ "type": "move", "x": 3 }));
  ```
- Differences from the original:
  - Received JSON calls the receive callback if there is one, otherwise it is collected and taken out with take_received_messages. (also added to the original, up to RECEIVED_MESSAGE_LIMIT, the oldest are dropped first on overflow)
  - disconnect, as in the original, only requests the close on the spot, and the disconnection counts from the next tick. (in the original onclose comes later, so is_connected stays true until then.
    ewebsock desktop does not send a Closed event when closed from this side, so it disconnects after taking out the remaining events in that tick)
  - Error events are notified as in the original and counted as disconnected. (the browser always sends onclose after onerror, and the ewebsock desktop thread ends after an error)
  - get_web_socket is ewebsock's sender (WsSender).
  - The receive callback is kept in an `Rc<RefCell>`. get_receive_event returns that Rc, and the caller borrows it with borrow_mut to call it.
  - wss:// on desktop is opened with ewebsock's "tls" feature (tungstenite's rustls and webpki root certificates). The rustls crypto provider is ring and is set on the first connection.
    Only with the engine's tls feature (on by default). If it is off, desktop opens only ws://.
  - Binary messages are also received if they are UTF-8 JSON. (also added to the original)

## WebSocketReceiveEvent (type)

Receive callback. ((received JSON))

```rust
pub type WebSocketReceiveEvent = Box<dyn FnMut(&Value)>
```

## WebSocketClient (struct) (Default)

WebSocket communication handler.
- The scene calls tick every frame to take out the queued events. Received JSON is taken by the receive callback if there is one, otherwise by take_received_messages.

Example: Connect from a scene and every frame take out what was received and reply (compile only, since it needs a network)

```rust
use vanilla::{Engine, Scene, SceneBase, WebSocketClient};

struct LobbyScene {
	scene_base: SceneBase,
	web_socket_client: WebSocketClient,
}

impl Scene for LobbyScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn load(&mut self, _engine: &Engine) {
		self.web_socket_client.connect("ws://localhost:8080");
	}

	fn tick(&mut self, _time_delta: f64) {
		self.web_socket_client.tick();
		for message in self.web_socket_client.take_received_messages() {
			if message["type"] == "ping" {
				self.web_socket_client.send(&serde_json::json!({ "type": "pong" }));
			}
		}
		self.web_socket_client.send(&serde_json::json!({ "type": "move", "x": 3 }));
	}
}
```

Example: Without a callback, received JSON is collected and taken out later (fed in with receive_message without connecting)

```rust
use vanilla::WebSocketClient;

let mut web_socket_client = WebSocketClient::new();
assert!(!web_socket_client.is_connected());
web_socket_client.send(&serde_json::json!({ "ignored": true }));
web_socket_client.receive_message(serde_json::json!({ "type": "hello", "id": 1 }));
web_socket_client.receive_message(serde_json::json!([1, 2, 3]));
let messages = web_socket_client.take_received_messages();
assert_eq!(messages.len(), 2);
assert_eq!(messages[0]["id"], 1);
assert!(web_socket_client.take_received_messages().is_empty());
```

- `pub fn new() -> WebSocketClient` (constructor, since 0.3.2): Constructor. (before connecting)
  - returns WebSocketClient: A handler that is not connected yet and has no receive callback.
- `pub fn connect(&mut self, url: &str)` (method, since 0.3.2): Connects. (does nothing if already connected. Once open, is_connected becomes true within the following ticks)
  - If the socket cannot be created, reports it to standard error and does nothing. If it fails to open, tick sees the error event and treats it as disconnected.
  - `url` &str: URL to connect to. (ws:// or wss://, wss:// on desktop only when the engine's tls feature is enabled)
- `pub fn disconnect(&mut self)` (method, since 0.3.2): Disconnects. (only when connected)
- `pub fn send(&mut self, value: &Value)` (method, since 0.3.2): Sends JSON. (only while connected)
  - Sent as a text message. Discarded if not connected yet.
  - `value` &Value: JSON value to send.
- `pub fn tick(&mut self)` (method, since 0.3.2): Update. (called every frame. Takes out accumulated events, changes the connection state and passes on received JSON)
- `pub fn receive_message(&mut self, value: Value)` (method, since 0.4.0): Passes on received JSON. (to the receive callback if there is one, otherwise collected to be taken out with take_received_messages, the original receiveMessage)
  - When RECEIVED_MESSAGE_LIMIT(1024) messages are collected, the oldest is discarded. If the callback is already borrowed (called again from inside the callback), it is discarded without being passed on.
  - `value` Value: Received JSON value. (goes through the same path even when the caller feeds it in directly)
- `pub fn take_received_messages(&mut self) -> Vec<Value>` (method, since 0.3.2): Takes out the collected received messages. (those collected while there was no receive callback, in received order)
  - returns Vec<Value>: List of collected JSON. (in receiving order, emptied when taken)
- `pub fn is_connected(&self) -> bool` (method, since 0.3.2): Returns whether connected.
  - returns bool: true if the open event was received and it is not disconnected yet. (still true until the next tick even after disconnect)
- `pub fn get_web_socket(&self) -> Option<&WsSender>` (method, since 0.3.2): Returns the WebSocket sender. (while trying to connect or connected)
  - returns Option<&WsSender>: ewebsock's sender. None if not connected yet or disconnected.
- `pub fn get_web_socket_mut(&mut self) -> Option<&mut WsSender>` (method, since 0.3.2): Returns the WebSocket sender. (for modification, for sending non-text messages directly)
  - returns Option<&mut WsSender>: ewebsock's sender. (mutable) None if not connected yet or disconnected.
- `pub fn set_receive_event(&mut self, receive_event: Option<WebSocketReceiveEvent>)` (method, since 0.3.2): Sets the receive callback. (if None, received messages are collected)
  - `receive_event` Option<WebSocketReceiveEvent>: Function that receives the received JSON. None turns it off and collects instead.

  Example: When the callback receives it, nothing is collected (the scene state is shared through `Rc<RefCell>`)

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::WebSocketClient;
  
  let score_list: Rc<RefCell<Vec<i64>>> = Rc::new(RefCell::new(Vec::new()));
  let score_list_for_event = score_list.clone();
  let mut web_socket_client = WebSocketClient::new();
  web_socket_client.set_receive_event(Some(Box::new(move |value: &serde_json::Value| {
  	if let Some(score) = value["score"].as_i64() {
  		score_list_for_event.borrow_mut().push(score);
  	}
  })));
  web_socket_client.receive_message(serde_json::json!({ "score": 42 }));
  assert_eq!(*score_list.borrow(), vec![42]);
  assert!(web_socket_client.take_received_messages().is_empty());
  ```

- `pub fn get_receive_event(&self) -> Option<Rc<RefCell<WebSocketReceiveEvent>>>` (method, since 0.3.2): Returns the receive callback. (borrow it with borrow_mut to call it)
  - returns Option<Rc<RefCell<WebSocketReceiveEvent>>>: `Rc<RefCell>` holding the receive callback. None if there is none.

## Functions and constants

- `pub const RECEIVED_MESSAGE_LIMIT: usize = 1024` (field, since 0.3.2): Limit on the number of messages collected while there is no receive callback.
  - returns usize
