Browse Source

Add example JavaScript app and code snippets to the README

tags/v0.1.0.1
Peter J. Jones 8 months ago
parent
commit
6cfa516b26
Signed by: Peter Jones <pjones@devalot.com> GPG Key ID: 9DAFAA8D01941E49
3 changed files with 160 additions and 3 deletions
  1. 48
    3
      README.md
  2. 88
    0
      examples/example.js
  3. 24
    0
      examples/index.html

+ 48
- 3
README.md View File

@@ -1,7 +1,52 @@
1
-# A Simple WebSocket Chat Server
1
+A Simple WebSocket Chat Server
2
+==============================
2 3
 
3 4
 This package includes a single executable: `wschat`.  It's an
4 5
 extremely simple chat server using WebSockets.
5 6
 
6
-The primary goal of this package is to provide students who are
7
-learning JavaScript a WebSocket server that they can talk to.
7
+The primary goal of this package is to provide a WebSocket server for
8
+students who are learning JavaScript so they have a real server to
9
+experiment with.
10
+
11
+Connecting from JavaScript
12
+--------------------------
13
+
14
+Before connecting you will need two pieces of information: the
15
+server's host name and an access code.  For this example we'll assume
16
+the following information:
17
+
18
+  | hostname    | example.com |
19
+  | access code | abc123      |
20
+
21
+Now we can construct a URL and open a connection:
22
+
23
+```javascript
24
+const socket = new WebSocket("wss://example.com/abc123");
25
+```
26
+
27
+*NOTE:* if your server doesn't support SSL/TLS you will have to
28
+replace `wss://` with `ws://`.
29
+
30
+All chat messages that are sent and received are JSON encoded objects
31
+that look like this:
32
+
33
+```javascript
34
+{
35
+  "sender": "name of message sender",
36
+  "content": "the content of the message"
37
+}
38
+```
39
+
40
+Here's an example of sending a message to the server:
41
+
42
+```javascript
43
+const message = {
44
+  sender: "Alice",
45
+  content: "Hello!"
46
+};
47
+
48
+socket.send(JSON.stringify(message));
49
+```
50
+
51
+A complete example using web components can be found in the `examples`
52
+directory.

+ 88
- 0
examples/example.js View File

@@ -0,0 +1,88 @@
1
+class ChatBox extends HTMLElement {
2
+  // Initialize a new chat box.
3
+  constructor() {
4
+    super();
5
+
6
+    const shadowRoot = this.attachShadow({mode: 'open'})
7
+    const template = document.getElementById("chat-template");
8
+    shadowRoot.appendChild(template.content.cloneNode(true));
9
+  }
10
+
11
+  // The custom element has been added to the DOM.
12
+  connectedCallback() {
13
+    try {
14
+      this.shadowRoot.querySelector('[type="submit"]').disabled = true;
15
+
16
+      const host = this.getAttribute("data-host");
17
+      const code = this.getAttribute("data-code");
18
+      const socket = new WebSocket(`wss://${host}/${code}`);
19
+
20
+      socket.onopen = () => {
21
+        this.shadowRoot.querySelector('[type="submit"]').disabled = false;
22
+      };
23
+
24
+      socket.onclose = () => {
25
+        this.chatConnectionClosed();
26
+      };
27
+
28
+      socket.onmessage = (e) => {
29
+        this.receiveChatMessage(JSON.parse(e.data));
30
+      };
31
+
32
+      socket.onerror = socket.onclose;
33
+
34
+      this.shadowRoot.querySelector("form")
35
+        .addEventListener("submit", (event) => {
36
+          event.preventDefault();
37
+          this.sendChatMessage(socket);
38
+        });
39
+    } catch (e) {
40
+      this.chatConnectionClosed();
41
+      throw e;
42
+    }
43
+  }
44
+
45
+  // An incoming message from the WebSocket server:
46
+  receiveChatMessage(msg) {
47
+    const li = document.createElement("li");
48
+
49
+    const sender = document.createElement("div");
50
+    sender.classList.add("sender");
51
+    sender.textContent = msg.sender;
52
+    li.appendChild(sender);
53
+
54
+    const content = document.createElement("div");
55
+    content.classList.add("content");
56
+    content.textContent = msg.content;
57
+    li.appendChild(content);
58
+
59
+    this.shadowRoot.querySelector("ul").appendChild(li);
60
+  }
61
+
62
+  // Send a message from the form to the server:
63
+  sendChatMessage(socket) {
64
+    const input = this.shadowRoot.querySelector('[name="content"]');
65
+    const content = input.value.trim();
66
+    if (content.length === 0) return;
67
+
68
+    const message = {
69
+      sender: this.getAttribute("data-user"),
70
+      content: content,
71
+    };
72
+
73
+    input.value = "";
74
+    socket.send(JSON.stringify(message));
75
+  }
76
+
77
+  // The connection is dead:
78
+  chatConnectionClosed() {
79
+    for (let i of Array.from(this.shadowRoot.querySelectorAll("input"))) {
80
+      i.disabled = true;
81
+    }
82
+
83
+    this.receiveChatMessage({sender: "browser", content: "Connection closed."});
84
+  }
85
+}
86
+
87
+// Register the custom element:
88
+customElements.define("chat-box", ChatBox);

+ 24
- 0
examples/index.html View File

@@ -0,0 +1,24 @@
1
+<!DOCTYPE html>
2
+<title>WebSocket Chat Example</title>
3
+<h1>WebSocket Chat Example</h1>
4
+
5
+<template id="chat-template">
6
+  <style>
7
+    ul { list-style-type: none; }
8
+    li { display: flex; }
9
+    .sender { font-style: italic; padding-right: 1em; }
10
+  </style>
11
+
12
+  <form>
13
+    <ul></ul>
14
+    <input type="text" name="content">
15
+    <input type="submit" value="Send">
16
+  </form>
17
+</template>
18
+
19
+<chat-box data-host="example.com"
20
+          data-code="abc123"
21
+          data-user="Alice">
22
+</chat-box>
23
+
24
+<script src="example.js"></script>

Loading…
Cancel
Save