Skip to content

Instantly share code, notes, and snippets.

@aricart
Created September 7, 2022 16:45
Show Gist options
  • Save aricart/6b7d77cf7b494fd25b091f134f76513c to your computer and use it in GitHub Desktop.
Save aricart/6b7d77cf7b494fd25b091f134f76513c to your computer and use it in GitHub Desktop.
TLS server connection example

To run this example:

mkdir test
cd test
npm init -y
npm install nats.ws

# Copy `server.go`, `chat.html` and `chat.js` to the `test` directory

# create a directory holding the certs
env CAROOT=./certs mkcert -cert-file ./certs/cert.pem -key-file ./certs/key.pem -install localhost 127.0.0.1 ::1

go run server.go

# in a different terminal start an http server - if you don't have deno installed see https://deno.land/#installation
deno run --allow-all --unstable https://deno.land/std@0.136.0/http/file_server.ts .

# open your browser by clicking on the URL printed by the command above to the chat.html, you should see the client connecting.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ws-nats chat</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
crossorigin="anonymous">
</head>
<!-- when the browser exits, we publish a message -->
<body onunload="chat.exiting()">
<!-- a form for entering messages -->
<div class="container">
<h1>ws-nats chat</h1>
<input type="text" class="form-control" id="data" placeholder="Message" autocomplete="off"><br/>
<button id="send" onclick="chat.send()" class="btn btn-primary">Send</button>
</div>
<br/>
<!-- a place to record messages -->
<div id="chats" class="container"></div>
<script type="module" src="chat.js"></script>
</body>
</html>
/*
* Copyright 2020 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { connect, JSONCodec } from "node_modules/nats.ws/esm/nats.js";
const me = Date.now();
window.chat = {
send: send,
exiting: exiting,
};
// create a decoder, the client is sending JSON
const jc = JSONCodec();
// create a connection, and register listeners
const init = async function () {
// if the connection doesn't resolve, an exception is thrown
// a real app would allow configuring the hostport and whether
// to use WSS or not.
const conn = await connect(
{ servers: "wss://localhost:9222" },
);
addEntry(`connected to ${conn.info.host}:${conn.info.port} - tls? ${conn.info.tls_required}` )
// handle connection to the server is closed - should disable the ui
conn.closed().then((err) => {
let m = "NATS connection closed";
addEntry(`${m} ${err ? err.message : ""}`);
});
(async () => {
for await (const s of conn.status()) {
addEntry(`Received status update: ${s.type}`);
}
})().then();
// the chat application listens for messages sent under the subject 'chat'
(async () => {
const chat = conn.subscribe("chat");
for await (const m of chat) {
const jm = jc.decode(m.data);
addEntry(
jm.id === me ? `(me): ${jm.m}` : `(${jm.id}): ${jm.m}`,
);
}
})().then();
// when a new browser joins, the joining browser publishes an 'enter' message
(async () => {
const enter = conn.subscribe("enter");
for await (const m of enter) {
const jm = jc.decode(m.data);
addEntry(`${jm.id} entered.`);
}
})().then();
(async () => {
const exit = conn.subscribe("exit");
for await (const m of exit) {
const jm = jc.decode(m.data);
if (jm.id !== me) {
addEntry(`${jm.id} exited.`);
}
}
})().then();
// we connected, and we publish our enter message
conn.publish("enter", jc.encode({ id: me }));
return conn;
};
init().then((conn) => {
window.nc = conn;
}).catch((ex) => {
addEntry(`Error connecting to NATS: ${ex}`);
});
// this is the input field
let input = document.getElementById("data");
// add a listener to detect edits. If they hit Enter, we publish it
input.addEventListener("keyup", (e) => {
if (e.key === "Enter") {
document.getElementById("send").click();
} else {
e.preventDefault();
}
});
// send a message if user typed one
function send() {
input = document.getElementById("data");
const m = input.value;
if (m !== "" && window.nc) {
window.nc.publish("chat", jc.encode({ id: me, m: m }));
input.value = "";
}
return false;
}
// send the exit message
function exiting() {
if (window.nc) {
window.nc.publish("exit", jc.encode({ id: me }));
}
}
// add an entry to the document
function addEntry(s) {
const p = document.createElement("pre");
p.appendChild(document.createTextNode(s));
document.getElementById("chats").appendChild(p);
}
package main
import (
"fmt"
"os"
"os/signal"
"runtime"
"syscall"
"time"
"github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats.go"
)
var ns *server.Server
func main() {
go func() {
// Initialize new server with options
var err error
opts := &server.Options{}
opts.Debug = true
opts.Trace = true
opts.Websocket.Port = 9222
opts.Websocket.Host = "127.0.0.1"
tc := &server.TLSConfigOpts{
CertFile: "/tmp/embed/certs/cert.pem",
KeyFile: "/tmp/embed/certs/key.pem",
CaFile: "/tmp/embed/certs/rootCA.pem",
}
opts.TLSConfig, err = server.GenTLSConfig(tc)
if err != nil {
panic(err.Error())
}
opts.Websocket.TLSConfig = opts.TLSConfig
ns, err = server.NewServer(opts)
if err != nil {
panic(err)
}
handleSignals()
ns.ConfigureLogger()
// Start the server via goroutine
go ns.Start()
// Wait for server to be ready for connections
if !ns.ReadyForConnections(4 * time.Second) {
panic("not ready for connection")
}
// Connect to server
nc, err := nats.Connect("nats://127.0.0.1",
nats.Secure(),
nats.RootCAs("/tmp/embed/certs/rootCA.pem"))
if err != nil {
panic(err)
}
subject := "my-subject"
// Subscribe to the subject
nc.Subscribe(subject, func(msg *nats.Msg) {
// Print message data
data := string(msg.Data)
fmt.Println(data)
nc.Close()
})
// Publish data to the subject
nc.Publish(subject, []byte("Hello embedded NATS!"))
}()
runtime.Goexit()
}
// handle signals
func handleSignals() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT)
go func() {
for sig := range c {
switch sig {
case syscall.SIGINT:
os.Exit(0)
}
}
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment