By dev-hemul
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!
Heya @devhemul,
Check the following question that was discussed a while back:
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 thews
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 usewss
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 to8080
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.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.