Princewill
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # How To Configure WebSocket Servers For Secure Connectors (Wss Protocol) WebSockets are a great way of improving your web applications to be faster and more responsive. They provide persistent bi-directional communication between a user and your server, making them unique. With WebSockets being prominent for their features, they are prone to attacks. Hence, you must become your own CA and enforce the use of SSL/TLS certificates to encrypt your server to secure it from attacks. In this article, you will learn how to set up your server, know what SSL/TLC certificates are and why they are necessary for setting up secure connectors, configure your server to ensure secure connections using SSL/TLC certificates, and ways to debug and monitor your application. ## Understanding WebSockets And WSS Protocols WebSockets are a communication protocol that uses a specific handshake process to connect users and servers. The handshake process upgrades the existing HTTP connection to a WebSocket connection. Once this occurs, the WebSocket protocol uses a specific method to ensure that the server sends the messages in the correct order. WebSockets are a must-have when creating dynamic and responsive web applications. It allows users and servers to have real-time communications. They also have low latency and reduced overhead, which helps improve any web application's performance. It combines the WebSocket protocol and the Secure Socket Layer(SSL). Unlike the traditional HTTP request, once a WebSocket is initiated, it does not need to reconnect after a response. ## Setting Up Your Server Selecting a suitable WebSocket server is determined by a few general factors. The first factor is the feature you would want your web application to have, e.g multi-languages. The next factor would be to estimate the application's traffic for the server and to ensure you get a server that can handle the load. Scalability and cost are the two last factors to consider. Below is a list of WebSockets available with React. Socket.IO [uWebsocket.js](https://www.npmjs.com/package/uwsjs/v/1.0.0) [SockJS](https://www.npmjs.com/package/sockjs) [WS](https://www.npmjs.com/package/ws) Below is a code sample showing a basic WebSocket server setup using Socket.io in React. > You should have [node.js](https://nodejs.org/en/docs) already installed on your local machine and create an `index.js` file for this application. ```javascript const express = require("express"); const app = express(); const http = require("http"); const server = http.createServer(app); app.get("/", (req, res) => { res.send("<h1>Hello world</h1>"); }); server.listen(3000, () => { console.log("listening on *:3000"); }); ``` This code creates a server on port 3000, it sends a welcome message and then listens for a message from the user. Once you run `node index.js` on your machine, this would be the output: ![first port message](https://hackmd.io/_uploads/HywNTxrcT.png) This is what your output should look like on the client side: ![UI image for hello world](https://hackmd.io/_uploads/HycITeS9p.png) You can expand the code by adding a `disconnection` and `connection` event. As shown with the code below: ```javascript const express = require("express"); const app = express(); const http = require("http"); const server = http.createServer(app); const { Server } = require("socket.io"); const io = new Server(server); app.get("/", (req, res) => { res.sendFile("<h1>Hello world</h1>"); }); io.on("connection", (socket) => { console.log("a user connected"); socket.on("disconnect", () => { console.log("user disconnected"); }); }); server.listen(3000, () => { console.log("listening on *:3000"); }); ``` This code is an expanded version of the first code, the only difference is the addition of `connection` and `disconnection` events that show when a user is connected or disconnected. >Note that when creating this server, using the `http` module and `server = http.createServer` makes the application not secure. When you you run `node index.js` on multiple tabs, this would be your output: ![listening on port 3000 connected](https://hackmd.io/_uploads/rkoV4tUop.png) While this image shows you the result of opening and closing multiple tabs: ![listening on port 3000 disconnected](https://hackmd.io/_uploads/B1F02qas6.png) ## Enabling Secure Connections Using SSL/TLS Certificates Most times, when opening applications online, your browser might alert you, giving you a warning that tells you the application you are about to enter is not secure. This simply means that application employs the use of traditional HTTP and is not secure. The image below shows what the error should look like: ![HTTP](https://hackmd.io/_uploads/B1OZ05aj6.jpg) A sure way of avoiding the error shown above is by becoming your Certificate Authority(CA) and then using the `wss` protocol for your server. The first step to becoming a CA is generating your private key using this: ```shell openssl genrsa -des3 -out myCA.key 2048 ``` After you have done that, you will be asked for a passphrase. This prevents anyone from generating a root certificate of their own if they get access to your private key. Your output should look like this: ![PEM pass phrase](https://hackmd.io/_uploads/BJCbRLy3a.jpg) >It is important that you do not skip this stage and ensure your passphrase is secure. Then you generate a root certificate. ```shell openssl req -x509 -new -nodes -key myCA.key -sha256 -days 1825 -out myCA.pem ``` You will be prompted to input the passphrase of your private key. A bunch of questions will be provided for you to answer, it should look like this: ![bunch of questions](https://hackmd.io/_uploads/HyPy0Ikna.jpg) >The common name should be something you will recognise easily as your root certificate in a list of other certificates. You should now have two files `myCA.key` that contains your private key and `myCA.pem` that contains your root certificate. ![cert verification](https://hackmd.io/_uploads/BJh40LJ36.jpg) > To become a fully functional CA, install your root certificates on all your devices. Since you are now a fully functional CA, to host a secure WebSocket server in node.js, you can use the sample code below: ```typescript import { Server as WebSocket } from "ws"; import { createServer as HttpsServer } from 'https'; import { readFileSync } from "fs"; server = HttpsServer({ cert: readFileSync('path/to/myCA.pem'), key: readFileSync('path/to/myCA.key') }) socket = new WebSocket({ server: server }); socket.on(...); server.listen(3000); ``` This code creates a server that imports the `ws` module, the `https` module, and the `fs` module to add security to your WebSocket server. `server = HttpsServer({...})` creates an HTTPS server that uses the `HttpsServer` function to configure the appropriate files. The `cert:readFileSync('...')` and `key:readFileSync('...')` loads the SSL certificate and SSL key from the specified path respectively. The `socket.on(...)` function is blank for you to add the necessary event listeners as needed. If you have followed the steps above, your application should come up on Chrome or any other Web browser as a secure connection as shown below: ![HTTPS](https://hackmd.io/_uploads/ryeiAqTs6.jpg) ## Monitoring and Logging There are many reasons why you should monitor and log your servers. Security is one of the primary reasons. WebSocket servers are prone to attacks, and monitoring your servers would help you predict and prevent these attacks from occurring. To help you track your server, you could take the following steps; * Choose a monitoring tool. e.g. [Prometheus](https://prometheus.io/), [Datadog](https://www.datadoghq.com/). * Configure the tool for specific alerts and notifications you want to look out for. * Choose a logging tool, e.g. [Splunk](https://www.splunk.com/), [Papertrail](https://www.papertrail.com/solution/log-management/). * Configure the logging tool. These tools help you predict potential attacks on your server and you must learn to analyze the data for protection. Examples of security threats you are looking for include; * Brute force attack, where an attacker tries to guess a user's password. * Denial of Service(DoS) attack, when your server(s) is overwhelmed by traffic from an attacker pushing out legitimate users. * Man-in-the-middle attack, where information is intercepted and one of the parties is impersonated. The code below shows you a `console.log` method for monitoring your server. ```javascript const io = require("socket.io-client"); const socket = io("https://localhost:3000"); socket.on("connect", () => { // Start logging all messages that are sent and received by the Socket.IO client console.log("Connected to the WebSocket server!"); socket.on("message", (message) => { console.log("Received message from the server: ${message}"); }); socket.on("disconnect", () => { console.log("Disconnected from the WebSocket server!"); }); }); ``` The code creates a Socket.io instance `socket` and connects it to a specified URL `https://localhost:3000`. It then sends a message when there is a connection or disconnection event. ## Testing And Debugging Testing your server for different issues and debugging your application would help it run smoothly. Common issues faced in WebSocket servers include; * Connection problems. * Message delivery problems. * Performance problems. * Security problems. The code below would help you attempt a basic testing of your server. ````javascript const io = require("socket.io-client"); const socket = io("http://localhost:3000"); socket.on("connect", () => { // Send a test message to the server socket.emit("message", "Hello, world!"); // Verify that the server responds correctly socket.on("message", (message) => { if (message !== "Hello from the server!") { throw new Error("Request failed.Unexpected response from the server"); } }); }); ```` The code establishes a Socket.io connection of a client connecting to your server, sends a message, and verifies the server's response as a means of basic testing. `if (message !==...)` would trigger an error message if the response gotten is not what is expected. This code is a performance tester. The error message should look like the image below: > Note: The appearance of your error message may vary based on how your HTML and CSS files are configured. ![error message from webpage](https://hackmd.io/_uploads/S10iw7Hcp.png) ## Conclusion In this article, you've learned what WebSockets are, why they differ from HTTPS, and why they should be secure. Most importantly, you have seen practical examples of how to set up your servers, implement secure connections, and manage them. Reading up on other articles about WebSockets can strengthen your knowledge on the topic. Luckily, some of the articles on the OpenReplay blog can help you [explore](https://blog.openreplay.com/exploring-web-sockets-for-real-time-communication/) WebSockets.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully