# web/websocketclient (vanilla.js 0.4.0)

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

WebSocket communication handler.

## WebSocketClient extends Object

WebSocket communication handler.
- A received JSON is passed to the receive callback if there is one, otherwise it is collected and taken out with takeReceivedMessages. (for games that take them out every frame)

Example: Receive received JSON with a callback or collect and take it out

```js
import { WebSocketClient } from "./build/vanilla.js";

const client = new WebSocketClient();
client.receiveMessage({ type: "hello" });
console.log(client.isConnected(), client.takeReceivedMessages().length);
client.setReceiveEvent((message) => {
	console.log(message.type);
});
client.receiveMessage({ type: "ping" });
console.log(client.getReceiveEvent() !== null);
```

- `constructor()` (constructor, since 0.0.11): Constructor.
- `connect(url)` (method, since 0.0.11): Connects.
  - `url` string: The WebSocket address to connect to. (ws:// or wss://, ignored if already connected)
- `receiveMessage(obj)` (method, since 0.4.0): Hands over received JSON. (to the callback if there is one, otherwise collected and taken out with takeReceivedMessages)
  - `obj` object: The received JSON object. (to the receive callback if there is one, otherwise collected)
- `takeReceivedMessages()` (method, since 0.4.0): Takes out the collected received messages. (those collected while there was no receive callback, in the order received, emptied once taken)
  - returns Array<object>: The collected received messages. (in the order received, emptied once taken)
- `tick()` (method, since 0.4.0): Update. (the browser hands events over as they happen so there is nothing to do, it exists so the same code works on platforms that must take events every frame)
- `disconnect()` (method, since 0.0.11): Disconnects.
- `send(obj)` (method, since 0.0.11): Sends JSON.
  - `obj` object: The JSON object to send. (not sent if not connected)
- `isConnected()` (method, since 0.0.11): Returns whether it is connected.
  - returns boolean: True if connected.
- `getWebSocket()` (method, since 0.0.11): Returns the WebSocket.
  - returns WebSocket | null: The inner WebSocket. (null if not connected)
- `setReceiveEvent(callback)` (method, since 0.0.11): Sets the receive event.
  - `callback` Function | null: The function that receives the received JSON object. (null goes back to collecting)
- `getReceiveEvent()` (method, since 0.0.11): Returns the receive event.
  - returns Function | null: The receive callback. (null if none)
