vanilladocs
vanillapunch.com
API / web/websocketclient

web/websocketclient

웹소켓 통신 처리기. (JSON 을 주고받는 클라이언트)

  • 원본 web/websocketclient.js 를 옮긴 것이다. connect / disconnect / send(JSON) / is_connected / set_receive_event 를 따른다.
  • 소켓은 ewebsock 0.8 이다. 데스크탑은 tungstenite 를 도는 스레드, 웹(wasm)은 브라우저 WebSocket 을 쓴다.
  • 원본은 브라우저가 onopen / onmessage / onclose 를 불러 준다. 러스트 판은 씬이 매 프레임 tick 을 불러 쌓인 사건을 꺼낸다. 읽은 JSON 은 원본처럼 receive_message 로 넘긴다. (부르는 쪽이 직접 넣을 수도 있다)
// 씬 create
self.web_socket_client.connect("ws://localhost:8080");
// 씬 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 }));
  • 원본과 다른 점:
  • 받은 JSON 은 수신 콜백이 있으면 그것을 부르고, 없으면 모아 두었다가 take_received_messages 로 꺼낸다. (원본에도 넣었다, 최대 RECEIVED_MESSAGE_LIMIT 개, 넘치면 오래된 것부터 버린다)
  • disconnect 는 원본처럼 그 자리에서는 닫기만 걸고, 끊긴 것은 다음 tick 에 친다. (원본은 onclose 가 뒤에 와서 그때까지 is_connected 가 참이다. ewebsock 데스크탑은 이쪽에서 닫으면 Closed 사건을 보내지 않아, 그 tick 에 남은 사건을 꺼낸 뒤 끊는다)
  • 오류 사건은 원본처럼 알리고, 끊긴 것으로 친다. (브라우저는 onerror 뒤에 늘 onclose 가 오고, ewebsock 데스크탑은 오류 뒤 스레드가 끝난다)
  • get_web_socket 은 ewebsock 의 송신기(WsSender)다.
  • 수신 콜백은 Rc<RefCell> 에 담는다. get_receive_event 는 그 Rc 를 돌려주고, 부르는 쪽은 borrow_mut 로 빌려 부른다.
  • 데스크탑의 wss:// 는 ewebsock 의 "tls" 기능(tungstenite 의 rustls 와 webpki 뿌리 인증서)으로 연다. rustls 의 암호 공급자는 ring 이고 처음 붙을 때 정한다. 엔진의 tls 기능(기본으로 켜짐)일 때만이다. 끄면 데스크탑은 ws:// 만 열린다.
  • 바이너리 메시지도 UTF-8 JSON 이면 받는다. (원본에도 넣었다)

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)
// 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)

WebSocketReceiveEventtype

소스source

수신 콜백. ((받은 JSON))

Receive callback. ((received JSON))

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

WebSocketClientstruct traits Default

짝Counterpart: vanilla.js WebSocketClient소스source

웹소켓 통신 처리기.

  • 씬이 매 프레임 tick 을 불러 쌓인 사건을 꺼낸다. 받은 JSON 은 수신 콜백이 있으면 콜백이, 없으면 take_received_messages 가 꺼낸다.

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)
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받은 JSON 은 콜백이 없으면 모아 두었다가 꺼낸다 (접속 없이 receive_message 로 넣는다)Without a callback, received JSON is collected and taken out later (fed in with receive_message without connecting)
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());
생성자constructorpub fn new() -> WebSocketClient#0.3.2 부터since 0.3.2소스source

생성. (접속 전)

Constructor. (before connecting)

반환ReturnsWebSocketClient 접속 전이고 수신 콜백이 없는 처리기.A handler that is not connected yet and has no receive callback.

짝Counterpart: vanilla.js WebSocketClient.constructor

메서드methodpub fn connect(&mut self, url: &str)#0.3.2 부터since 0.3.2소스source

접속. (이미 접속돼 있으면 아무것도 하지 않는다. 열리면 다음 tick 들 사이에 is_connected 가 true 가 된다)

  • 소켓을 만들지 못하면 표준 에러에 알리고 아무것도 하지 않는다. 열리지 못하면 tick 이 오류 사건을 보고 끊긴 것으로 친다.

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
접속할 주소. (ws:// 나 wss://, 데스크탑의 wss:// 는 엔진의 tls 기능이 켜져 있을 때만)URL to connect to. (ws:// or wss://, wss:// on desktop only when the engine's tls feature is enabled)

짝Counterpart: vanilla.js WebSocketClient.connect

메서드methodpub fn disconnect(&mut self)#0.3.2 부터since 0.3.2소스source

접속 해제. (접속돼 있을 때만)

Disconnects. (only when connected)

짝Counterpart: vanilla.js WebSocketClient.disconnect

메서드methodpub fn send(&mut self, value: &Value)#0.3.2 부터since 0.3.2소스source

JSON 송신. (접속돼 있을 때만)

  • 글 메시지로 보낸다. 접속 전이면 버린다.

Sends JSON. (only while connected)

  • Sent as a text message. Discarded if not connected yet.
value&Value
보낼 JSON 값.JSON value to send.

짝Counterpart: vanilla.js WebSocketClient.send

메서드methodpub fn tick(&mut self)#0.3.2 부터since 0.3.2소스source

갱신. (매 프레임 부른다. 쌓인 사건을 꺼내 접속 상태를 바꾸고 받은 JSON 을 넘긴다)

Update. (called every frame. Takes out accumulated events, changes the connection state and passes on received JSON)

짝Counterpart: vanilla.js WebSocketClient.tick

메서드methodpub fn receive_message(&mut self, value: Value)#0.4.0 부터since 0.4.0소스source

받은 JSON 넘기기. (수신 콜백이 있으면 콜백, 없으면 모아 두었다가 take_received_messages 로 꺼낸다, 원본 receiveMessage)

  • 모아 둔 것이 RECEIVED_MESSAGE_LIMIT(1024) 개면 가장 오래된 것을 버린다. 콜백이 이미 빌려져 있으면(콜백 안에서 다시 부르면) 넘기지 않고 버린다.

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.
valueValue
받은 JSON 값. (부르는 쪽이 직접 넣어도 같은 길을 지난다)Received JSON value. (goes through the same path even when the caller feeds it in directly)

짝Counterpart: vanilla.js WebSocketClient.receiveMessage

메서드methodpub fn take_received_messages(&mut self) -> Vec<Value>#0.3.2 부터since 0.3.2소스source

모아 둔 받은 메시지 꺼내기. (수신 콜백이 없을 때 모인 것, 받은 차례)

Takes out the collected received messages. (those collected while there was no receive callback, in received order)

반환ReturnsVec<Value> 모아 둔 JSON 목록. (받은 차례, 꺼내면 비운다)List of collected JSON. (in receiving order, emptied when taken)

짝Counterpart: vanilla.js WebSocketClient.takeReceivedMessages

메서드methodpub fn is_connected(&self) -> bool#0.3.2 부터since 0.3.2소스source

접속 여부 반환.

Returns whether connected.

반환Returnsbool 열림 사건을 받았고 아직 끊기지 않았으면 true. (disconnect 뒤에도 다음 tick 까지는 true)true if the open event was received and it is not disconnected yet. (still true until the next tick even after disconnect)

짝Counterpart: vanilla.js WebSocketClient.isConnected

메서드methodpub fn get_web_socket(&self) -> Option<&WsSender>#0.3.2 부터since 0.3.2소스source

웹소켓 송신기 반환. (접속 시도 중이거나 접속돼 있을 때)

Returns the WebSocket sender. (while trying to connect or connected)

반환ReturnsOption<&WsSender> ewebsock 의 송신기. 접속 전이거나 끊겼으면 None.ewebsock's sender. None if not connected yet or disconnected.

짝Counterpart: vanilla.js WebSocketClient.getWebSocket

메서드methodpub fn get_web_socket_mut(&mut self) -> Option<&mut WsSender>#0.3.2 부터since 0.3.2소스source

웹소켓 송신기 반환. (변경용, 글이 아닌 메시지를 직접 보낼 때)

Returns the WebSocket sender. (for modification, for sending non-text messages directly)

반환ReturnsOption<&mut WsSender> ewebsock 의 송신기. (변경용) 접속 전이거나 끊겼으면 None.ewebsock's sender. (mutable) None if not connected yet or disconnected.

짝Counterpart: vanilla.js WebSocketClient.getWebSocket

메서드methodpub fn set_receive_event(&mut self, receive_event: Option<WebSocketReceiveEvent>)#0.3.2 부터since 0.3.2소스source

수신 콜백 설정. (None 이면 받은 메시지를 모아 둔다)

Sets the receive callback. (if None, received messages are collected)

receive_eventOption<WebSocketReceiveEvent>
받은 JSON 을 넘겨받을 함수. None 이면 끄고 모아 둔다.Function that receives the received JSON. None turns it off and collects instead.

짝Counterpart: vanilla.js WebSocketClient.setReceiveEvent

예제Example콜백이 받으면 모으지 않는다 (씬 상태는 `Rc<RefCell>` 로 나눠 쥔다)When the callback receives it, nothing is collected (the scene state is shared through `Rc<RefCell>`)
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());
메서드methodpub fn get_receive_event(&self) -> Option<Rc<RefCell<WebSocketReceiveEvent>>>#0.3.2 부터since 0.3.2소스source

수신 콜백 반환. (부를 때는 borrow_mut 로 빌린다)

Returns the receive callback. (borrow it with borrow_mut to call it)

반환ReturnsOption<Rc<RefCell<WebSocketReceiveEvent>>> 수신 콜백을 담은 Rc<RefCell>. 없으면 None.Rc<RefCell> holding the receive callback. None if there is none.

짝Counterpart: vanilla.js WebSocketClient.getReceiveEvent

상수Constants

상수constantpub const RECEIVED_MESSAGE_LIMIT: usize = 1024#0.3.2 부터since 0.3.2소스source

수신 콜백이 없을 때 모아 두는 메시지 수 한도.

Limit on the number of messages collected while there is no receive callback.

반환Returnsusize