Browse Source

Add example JavaScript app and code snippets to the README

tags/v0.1.0.1
Peter J. Jones 1 year 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 @@
# A Simple WebSocket Chat Server
A Simple WebSocket Chat Server
==============================

This package includes a single executable: `wschat`. It's an
extremely simple chat server using WebSockets.

The primary goal of this package is to provide students who are
learning JavaScript a WebSocket server that they can talk to.
The primary goal of this package is to provide a WebSocket server for
students who are learning JavaScript so they have a real server to
experiment with.

Connecting from JavaScript
--------------------------

Before connecting you will need two pieces of information: the
server's host name and an access code. For this example we'll assume
the following information:

| hostname | example.com |
| access code | abc123 |

Now we can construct a URL and open a connection:

```javascript
const socket = new WebSocket("wss://example.com/abc123");
```

*NOTE:* if your server doesn't support SSL/TLS you will have to
replace `wss://` with `ws://`.

All chat messages that are sent and received are JSON encoded objects
that look like this:

```javascript
{
"sender": "name of message sender",
"content": "the content of the message"
}
```

Here's an example of sending a message to the server:

```javascript
const message = {
sender: "Alice",
content: "Hello!"
};

socket.send(JSON.stringify(message));
```

A complete example using web components can be found in the `examples`
directory.

+ 88
- 0
examples/example.js View File

@@ -0,0 +1,88 @@
class ChatBox extends HTMLElement {
// Initialize a new chat box.
constructor() {
super();

const shadowRoot = this.attachShadow({mode: 'open'})
const template = document.getElementById("chat-template");
shadowRoot.appendChild(template.content.cloneNode(true));
}

// The custom element has been added to the DOM.
connectedCallback() {
try {
this.shadowRoot.querySelector('[type="submit"]').disabled = true;

const host = this.getAttribute("data-host");
const code = this.getAttribute("data-code");
const socket = new WebSocket(`wss://${host}/${code}`);

socket.onopen = () => {
this.shadowRoot.querySelector('[type="submit"]').disabled = false;
};

socket.onclose = () => {
this.chatConnectionClosed();
};

socket.onmessage = (e) => {
this.receiveChatMessage(JSON.parse(e.data));
};

socket.onerror = socket.onclose;

this.shadowRoot.querySelector("form")
.addEventListener("submit", (event) => {
event.preventDefault();
this.sendChatMessage(socket);
});
} catch (e) {
this.chatConnectionClosed();
throw e;
}
}

// An incoming message from the WebSocket server:
receiveChatMessage(msg) {
const li = document.createElement("li");

const sender = document.createElement("div");
sender.classList.add("sender");
sender.textContent = msg.sender;
li.appendChild(sender);

const content = document.createElement("div");
content.classList.add("content");
content.textContent = msg.content;
li.appendChild(content);

this.shadowRoot.querySelector("ul").appendChild(li);
}

// Send a message from the form to the server:
sendChatMessage(socket) {
const input = this.shadowRoot.querySelector('[name="content"]');
const content = input.value.trim();
if (content.length === 0) return;

const message = {
sender: this.getAttribute("data-user"),
content: content,
};

input.value = "";
socket.send(JSON.stringify(message));
}

// The connection is dead:
chatConnectionClosed() {
for (let i of Array.from(this.shadowRoot.querySelectorAll("input"))) {
i.disabled = true;
}

this.receiveChatMessage({sender: "browser", content: "Connection closed."});
}
}

// Register the custom element:
customElements.define("chat-box", ChatBox);

+ 24
- 0
examples/index.html View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<title>WebSocket Chat Example</title>
<h1>WebSocket Chat Example</h1>

<template id="chat-template">
<style>
ul { list-style-type: none; }
li { display: flex; }
.sender { font-style: italic; padding-right: 1em; }
</style>

<form>
<ul></ul>
<input type="text" name="content">
<input type="submit" value="Send">
</form>
</template>

<chat-box data-host="example.com"
data-code="abc123"
data-user="Alice">
</chat-box>

<script src="example.js"></script>

Loading…
Cancel
Save