# web/websocketclient (vanilla.js 0.4.0)

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

웹소켓 통신 처리기.

## WebSocketClient extends Object

웹소켓 통신 처리기.
- 받은 JSON 은 수신 콜백이 있으면 그것을 부르고, 없으면 모아 두었다가 takeReceivedMessages 로 꺼낸다. (매 프레임 꺼내 쓰는 게임용)

예제: 받은 JSON 을 콜백으로 받거나 모아서 꺼내기

```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): 생성.
- `connect(url)` (method, since 0.0.11): 접속.
  - `url` string: 접속할 웹소켓 주소. (ws:// 나 wss://, 이미 접속 중이면 무시한다)
- `receiveMessage(obj)` (method, since 0.4.0): 받은 JSON 넘기기. (수신 콜백이 있으면 콜백, 없으면 모아 두었다가 takeReceivedMessages 로 꺼낸다)
  - `obj` object: 받은 JSON 객체. (수신 콜백이 있으면 콜백으로, 없으면 모아 둔다)
- `takeReceivedMessages()` (method, since 0.4.0): 모아 둔 받은 메시지 꺼내기. (수신 콜백이 없을 때 모인 것, 받은 차례, 꺼내면 비운다)
  - returns Array<object>: 모아 둔 받은 메시지. (받은 차례, 꺼내면 비운다)
- `tick()` (method, since 0.4.0): 갱신. (브라우저가 사건을 그때그때 넘겨 할 일이 없다, 매 프레임 사건을 꺼내야 하는 플랫폼과 같은 코드로 쓰려고 둔다)
- `disconnect()` (method, since 0.0.11): 접속 해제.
- `send(obj)` (method, since 0.0.11): JSON 송신.
  - `obj` object: 보낼 JSON 객체. (접속 중이 아니면 보내지 않는다)
- `isConnected()` (method, since 0.0.11): 접속 여부 반환.
  - returns boolean: 접속 중이면 참.
- `getWebSocket()` (method, since 0.0.11): 웹소켓 반환.
  - returns WebSocket | null: 안쪽 웹소켓. (접속하지 않았으면 null)
- `setReceiveEvent(callback)` (method, since 0.0.11): 수신 이벤트 설정.
  - `callback` Function | null: 받은 JSON 객체를 넘겨 받을 함수. (null 이면 모아 두는 쪽으로 돌아간다)
- `getReceiveEvent()` (method, since 0.0.11): 수신 이벤트 반환.
  - returns Function | null: 수신 콜백. (없으면 null)
