Skip to content

Latest commit

 

History

History

websocket-server

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Websocket Server Example (2.x)

This example demonstrates how to extend the default Front-Commerce Express HTTP server to add websocket capabilities.

Why?

Websockets are a useful tool to enable real-time communication between the server and the client. This can be useful for chat applications, real-time notifications, or any other use case where you need to push data from the server to the client.

What?

This example uses the module.config.js::onServerInit callback introduced in Front-Commerce 2.30 to add a websocket server to the Express server.

⚠ This example is a basic implementation and does not handle any security or scalability concerns. Using websockets in production requires additional considerations and is out of the scope of this example. You may also consider alternatives such as Server Sent Events or WebRTC depending on your use case.

Usage

  1. Add the examples module to your project (see ../README.md)
  2. Install new dependencies:
npm install ws
  1. Register the examples/websocket-server module and theme in your project:
--- a/.front-commerce.js
+++ b/.front-commerce.js
@@ -2,16 +2,12 @@ module.exports = {
   name: "Front-Commerce Skeleton",
   url: "http://localhost:4000",
   modules: [
+    "./examples/websocket-server",
     "./node_modules/front-commerce/theme-chocolatine",
     "./src",
   ],
    serverModules: [
      { name: "FrontCommerce", path: "server/modules/front-commerce" },
    ],
    webModules: [
     { name: "FrontCommerce", path: "front-commerce/src/web" },
     { name: "ThemeChocolatine", path: "front-commerce/theme-chocolatine/web" },
+    { name: "WebsocketServer", path: "./examples/websocket-server/web" },
     { name: "Skeleton", path: "./src/web" },
   ],
 };

Test

Open http://localhost:4000/ in your browser. You should see a simple page asking for your name. Once you enter your name, you should see a welcome message and an input field to send messages to the server.

When you send a message, the server will broadcast it to all connected clients.

Open the same page in another tab or in another browser. You should see the chat history and be able to send messages from both clients in real-time.

Demo

vokoscreenNG-2024-06-05_17-09-05.mp4