Implementing WebSocket communication in Marko.js involves setting up a WebSocket server to handle connections and events, and integrating WebSocket functionality into your Marko.js templates to send and receive messages in real-time. Here's a step-by-step guide on how to implement WebSocket communication in a Marko.js project:
1. Setup your Project
Create a new project directory and initialize a new Node.js project:
mkdir marko-websocket
cd marko-websocket
npm init -y
2. Install Dependencies
Install the necessary packages:
npm install marko express @marko/express ws
marko
: The Marko.js library.
express
: The Express.js framework for creating the server.
@marko/express
: Middleware for using Marko.js with Express.
ws
: WebSocket library for Node.js.
3. Project Structure
Organize your project directory like this:
marko-websocket/
├── src/
│ ├── components/
│ ├── pages/
│ │ ├── index.marko
│ ├── layouts/
│ │ ├── main.marko
│ ├── server.js
├── package.json
4. Create Page Templates
Create the main layout template in src/layouts/main.marko
:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${input.title}</title>
</head>
<body>
<header>
<h1>${input.title}</h1>
</header>
<main>
<${input.body} />
</main>
</body>
</html>
Create the homepage template in src/pages/index.marko
:
<layout-use template="../../layouts/main.marko">
<layout-put into="title">WebSocket Chat</layout-put>
<layout-put into="body">
<div id="chat">
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
</div>
</layout-put>
</layout-use>
<script>
const ws = new WebSocket('ws://localhost:3000');
const form = document.querySelector('form');
const input = document.querySelector('#input');
form.addEventListener('submit', function(event) {
event.preventDefault();
if (input.value) {
ws.send(input.value);
input.value = '';
}
});
ws.onmessage = function(event) {
const messages = document.querySelector('#messages');
const li = document.createElement('li');
li.textContent = event.data;
messages.appendChild(li);
};
</script>
5. Setup the WebSocket Server
Create src/server.js
to set up the Express server and WebSocket server:
const express = require('express');
const markoMiddleware = require('@marko/express').default;
const WebSocket = require('ws');
const app = express();
const wss = new WebSocket.Server({ port: 3000 });
app.use(markoMiddleware());
app.get('/', (req, res) => {
res.marko(require('./pages/index.marko'));
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
6. Run Your Application
Start your application by running:
node src/server.js
Now, open your browser and navigate to http://localhost:3000
to see the WebSocket chat application. You can open multiple browser windows and chat between them in real-time.
This setup provides a basic WebSocket chat application with Marko.js, Express.js, and the ws
library. You can expand this application by adding features such as user authentication, private messaging, and message persistence. WebSocket communication enables real-time interaction between clients and is useful for building collaborative applications, live chat systems, and multiplayer games.