MCPcopy Index your code
hub / github.com/pywebio/PyWebIO / WebSocketSession

Class WebSocketSession

webiojs/src/session.ts:52–176  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

50}
51
52export class WebSocketSession implements Session {
53 ws: WebSocket;
54 debug: boolean;
55 webio_session_id: string = 'NEW';
56 private _closed: boolean; // session logic closed (by `close_session` command)
57 private _session_create_ts = 0;
58 private _session_create_callbacks: (() => void)[] = [];
59 private _session_close_callbacks: (() => void)[] = [];
60 private _on_server_message: (msg: Command) => any = () => {
61 };
62
63 constructor(public ws_api: string, public app_name: string = 'index') {
64 this.ws = null;
65 this.debug = false;
66 this._closed = false;
67 }
68
69 set_ws_api() {
70 let url = new URL(this.ws_api);
71 if (url.protocol !== 'wss:' && url.protocol !== 'ws:') {
72 let protocol = url.protocol || window.location.protocol;
73 url.protocol = protocol.replace('https', 'wss').replace('http', 'ws');
74 }
75 url.search = `?app=${this.app_name}&session=${this.webio_session_id}`;
76 this.ws_api = url.href;
77 }
78
79 on_session_create(callback: () => any): void {
80 this._session_create_callbacks.push(callback);
81 };
82
83 on_session_close(callback: () => any): void {
84 this._session_close_callbacks.push(callback);
85 }
86
87 on_server_message(callback: (msg: Command) => any): void {
88 this._on_server_message = callback;
89 }
90
91 start_session(debug: boolean = false): void {
92 let that = this;
93
94 this.set_ws_api();
95
96 this._session_create_ts = Date.now();
97 this.debug = debug;
98 this.ws = new WebSocket(this.ws_api);
99 this.ws.onopen = () => {
100 safe_poprun_callbacks(this._session_create_callbacks, 'session_create_callback');
101 };
102
103 this.ws.onclose = function (evt) {
104 if (!that._closed && that.webio_session_id != 'NEW') { // not receive `close_session` command && enabled reconnection
105 const session_create_interval = 5000;
106 if (Date.now() - that._session_create_ts > session_create_interval)
107 that.start_session(that.debug);
108 else
109 setTimeout(() => {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…