Question

How to create websocket conection?

I have node.js, express.js app width websocket

I create app platform

I have this client code:

let form = document.querySelector(".form");
let messagesDiv = document.getElementById("messages");
let formArea = document.querySelector(".form__area");

let sendMessage = () => {
    let formData = new FormData(form);
    let formDataValue = formData.get("text"); // Получаем значение конкретного поля, например "text"

    console.log("Отправляем значение:", formDataValue);

    if (socket.readyState === WebSocket.OPEN) {
        socket.send(formDataValue); // Отправляем только значение поля
        formArea.value = "";
    } else {
        console.log("WebSocket not connected");
    }
}

form.addEventListener("submit", (e) => {
    e.preventDefault();
    sendMessage();
});

formArea.addEventListener("keydown", (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
});

const url = 'ws://localhost:7000';
const socket = new WebSocket(url);

socket.onmessage = (e) => {
    console.log('Received data:', e.data);

    let messageElement = document.createElement('p');
    messageElement.textContent = e.data;

    messagesDiv.appendChild(messageElement);
}

socket.onopen = (e) => {
    console.log("WebSocket connection established");
}

And this server code:

import { WebSocketServer } from 'ws';

const run = async () => {
    const wss = new WebSocketServer({ port: 7000 });

    const clients = new Set();

    wss.on('connection', (ws) => {
        console.log('Client connected!');
        clients.add(ws);

        ws.on('message', (data) => {
            // Преобразуем данные в строку
            const message = typeof data === 'string' ? data : data.toString();
            console.log('Received data:', message);

            // Отправляем данные обратно всем подключённым клиентам
            clients.forEach(client => {
                if (client.readyState === WebSocket.OPEN) {
                    client.send(message);
                }
            });
        });

        ws.on('close', () => {
            console.log('Client disconnected');
            clients.delete(ws);
        });
    });

    console.log('WebSocket server is running on ws://localhost:7000');
};

export default run;

But, after deploy console write “WebSocket connection failed”

Why? What should i do?


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

KFSys
Site Moderator
Site Moderator badge
August 14, 2024

Heya @devhemul,

Check the following question that was discussed a while back:

https://www.digitalocean.com/community/questions/websocket-client-can-t-connect-to-the-server-on-digitalocean-app-platform

Let me quote one of the answers:

Hi there,

There are a couple of things I could suggest here:

  • Verify your Websocket Scheme:

    The code for this app included a conditional statement that checked whether the client was connecting over HTTPS. If it was, the server would attempt to use the wss protocol to make a connection. Otherwise, it would attempt to use the ws protocol.

    const protocol = window.location.protocol.includes('https') ? 'wss': 'ws'
    const ws = new WebSocket(`${protocol}://${location.host}`);
    

    When you ran this app locally, the app was not using SSL, and therefore used the ws protocol. On App Platform, apps will always run over HTTPS with SSL. Please verify that the app is able to use wss when deploying a new websocket app to app platform.

  • Externally Expose Your Service and Check that the Port is Correct

    Please make sure that your service is exposed externally. If your code only exposes localhost or if you are using an App Platform worker instead of a service, you will not be able to reach your application externally. In this tutorial, the app is exposed on port 8080. If you’re having trouble accessing the app, ensure that the app’s HTTP port is set to 8080 in the App’s spec.

In case that you are still seeing the problem, feel free to share a link to your GitHub project here so I could try deploying it for further investigation.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
Animation showing a Droplet being created in the DigitalOcean Cloud console