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?
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!
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.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
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: