websocket을 사용하려면 따로 설정파일 세팅해야함
websocket {
# Specify a host and port to listen for websocket connections
#
# listen: "host:port"
# It can also be configured with individual parameters,
# namely host and port.
#
# host: "hostname"
# port: 443
port: 8282
# This will optionally specify what host:port for websocket
# connections to be advertised in the cluster.
#
# advertise: "host:port"
# TLS configuration is required by default
#
#tls {
#cert_file: "/path/to/cert.pem"
#key_file: "/path/to/key.pem"
#}
# For test environments, you can disable the need for TLS
# by explicitly setting this option to `true`
#
no_tls: true
# [Cross-origin resource sharing option](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).
#
# IMPORTANT! This option is used only when the http request presents an Origin
# header, which is the case for web browsers. If no Origin header is present,
# this check will not be performed.
#
# When set to `true`, the HTTP origin header must match the request’s hostname.
# The default is `false`.
#
#same_origin: true
# [Cross-origin resource sharing option](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).
#
# IMPORTANT! This option is used only when the http request presents an Origin
# header, which is the case for web browsers. If no Origin header is present,
# this check will not be performed.
#
# List of accepted origins. When empty, and `same_origin` is `false`, clients from any origin are allowed to connect.
# This list specifies the only accepted values for the client's request Origin header. The scheme,
# host and port must match. By convention, the absence of TCP port in the URL will be port 80
# for an "http://" scheme, and 443 for "https://".
#
# allowed_origins [
# "http://www.example.com"
# "https://www.other-example.com"
# ]
# This enables support for compressed websocket frames
# in the server. For compression to be used, both server
# and client have to support it.
#
# compression: true
# This is the total time allowed for the server to
# read the client request and write the response back
# to the client. This includes the time needed for the
# TLS handshake.
#
# handshake_timeout: "2s"
# Name for an HTTP cookie, that if present will be used as a client JWT.
# If the client specifies a JWT in the CONNECT protocol, this option is ignored.
# The cookie should be set by the HTTP server as described [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies).
# This setting is useful when generating NATS `Bearer` client JWTs as the
# result of some authentication mechanism. The HTTP server after correct
# authentication can issue a JWT for the user, that is set securely preventing
# access by unintended scripts. Note these JWTs must be [NATS JWTs](https://docs.nats.io/nats-server/configuration/securing_nats/jwt).
#
# jwt_cookie: "my_jwt_cookie_name"
# If no user name is provided when a websocket client connects, will default
# this user name in the authentication phase. If specified, this will
# override, for websocket clients, any `no_auth_user` value defined in the
# main configuration file.
# Note that this is not compatible with running the server in operator mode.
#
# no_auth_user: "my_username_for_apps_not_providing_credentials"
# See below to know what is the normal way of limiting websocket clients
# to specific users.
# If there are no users specified in the configuration, this simple authorization
# block allows you to override the values that would be configured in the
# equivalent block in the main section.
#
# authorization {
# # If this is specified, the client has to provide the same username
# # and password to be able to connect.
# # username: "my_user_name"
# # password: "my_password"
#
# # If this is specified, the password field in the CONNECT has to
# # match this token.
# # token: "my_token"
#
# # This overrides the main's authorization timeout. For consistency
# # with the main's authorization configuration block, this is expressed
# # as a number of seconds.
# # timeout: 2.0
#}
}
html 소스
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NATS WebSocket Client</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; }
input, button { margin: 5px; padding: 10px; }
#messages { border: 1px solid #ccc; padding: 10px; width: 300px; margin: auto; height: 200px; overflow-y: scroll; }
</style>
</head>
<body>
<h2>NATS WebSocket Client</h2>
<div>
<input type="text" id="messageInput" placeholder="Enter message">
<button id="sendButton">Send</button> </div>
<h3>Received Messages</h3>
<div id="messages"></div>
<script type="module">
import { connect, StringCodec, JSONCodec } from "https://unpkg.com/nats.ws@latest/esm/nats.js";
const nc = await connect({ servers: "ws://localhost:8282" });
console.log("NATS에 연결됨");
const sc = StringCodec();
const jc = JSONCodec();
const subject = "test";
const sub = nc.subscribe(subject);
(async () => {
for await (const m of sub) {
try {
// Assuming the message is a string
const decodedString = sc.decode(m.data);
displayMessage(decodedString);
} catch (err){
//if can't decode as string it will be decoded as json
const decodedJson = jc.decode(m.data)
displayMessage(JSON.stringify(decodedJson))
}
}
})();
async function sendMessage() {
let message = document.getElementById("messageInput").value;
if (!message) return;
try {
//nc.publish(subject, sc.encode(message))
nc.publish(subject, jc.encode({data: message}))
displayMessage(`(Sent) ${message}`, true);
document.getElementById("messageInput").value = "";
} catch (err) {
console.error("Message send error", err);
}
}
// Get the button element
const sendButton = document.getElementById("sendButton");
// Add an event listener to the button
sendButton.addEventListener("click", sendMessage);
function displayMessage(msg, isSent = false) {
let msgDiv = document.getElementById("messages");
let newMessage = document.createElement("div");
newMessage.textContent = isSent ? `📤 ${msg}` : `📩 ${msg}`;
msgDiv.appendChild(newMessage);
msgDiv.scrollTop = msgDiv.scrollHeight;
}
// Handle connection close
nc.closed()
.then(() => {
console.log("NATS connection closed.");
})
.catch((err) => {
console.error("NATS connection closed with error:", err);
});
</script>
</body>
</html>