From 25a631896da425944657162c4d55f21951ebacfa Mon Sep 17 00:00:00 2001 From: "Thanh-Giang (River) Tan Nguyen" Date: Wed, 9 Jul 2025 00:03:40 +0700 Subject: [PATCH] update websocket example --- websocket-chat/app/static/index.html | 200 +++++++++++++++------------ 1 file changed, 109 insertions(+), 91 deletions(-) diff --git a/websocket-chat/app/static/index.html b/websocket-chat/app/static/index.html index 2221754..eacff12 100644 --- a/websocket-chat/app/static/index.html +++ b/websocket-chat/app/static/index.html @@ -1,100 +1,118 @@ - - - BlackSheep WebSocket Example - - - - -
-

Your client ID is {{ CLIENT_ID }}

-

Status: {{ status }}

-

Messages:

- -
- - - - -
-
- + + + +
+

Your client ID is {{ CLIENT_ID }}

+

Status: {{ status }}

- const app = { - data() { - return { - messages: [], - messageText: "", - ws: null, - status: "Disconnected", - WS_URL, - CLIENT_ID - } - }, - methods: { - makeMessage() { - return { - author: this.CLIENT_ID, - text: this.messageText, - timestamp: new Date().toISOString() - } - }, - submit() { - const message = this.makeMessage() - this.ws.send(JSON.stringify(message)) - this.messageText = "" - }, - connect(url) { - const ws = new WebSocket(url) +

Messages:

+ - ws.addEventListener("open", (evt) => { - this.status = "Connected" - console.log("Open", evt) - }) +
+ + + + +
+
- ws.addEventListener("message", (evt) => { - this.messages.push(JSON.parse(evt.data)) - console.log("Message", evt) - }) + - - \ No newline at end of file + this.ws.addEventListener("close", () => { + this.status = "Disconnected"; + this.ws = null; + }); + + this.ws.addEventListener("error", (event) => { + this.status = "Error"; + console.error("WebSocket error:", event); + }); + }, + disconnect() { + if (this.ws) { + this.ws.close(); + this.ws = null; + this.messages = []; + } + }, + renderTimestamp(ts) { + return new Date(ts).toLocaleTimeString(); + }, + }, + }).mount("#app"); + + +