#javascript #node.js #websocket #ws
Вопрос:
Мой сервер websocket не получает никакой информации. Сообщения от моего клиента websocket не доходят, но наоборот это работает. Т. е. клиент получает сообщение «Я подключен к вам» с сервера, и сокет открывается.
Полное server.js
const express = require('express');
const app = express();
const path = require('path');
app.use('/public', express.static(__dirname '/public'));
app.get('/', (req, res) => {
console.log('express connection');
res.sendFile(path.join(__dirname, '/public/index.html'));
});
const http = require('http');
const server = http.createServer(app);
let PORT = process.env.PORT;
if (PORT == null || PORT == '') {
PORT = 3000;
};
const fs = require('fs');
const ws = require('ws');
const wsServer = new ws.Server({ server: server});
wsServer.on('connection', (client) => {
client.send("I'm connected to you!");
});
wsServer.on('request', (req) => {
console.log(req);
});
wsServer.on('data', (message) => {
console.log(message);
});
server.listen(PORT, () => {
console.log('Websocket server started at ' PORT );
});
Наиболее важные части из client.js
var socket = new WebSocket('ws://localhost:3000');
// When the socket is open, send some data to the server
socket.onopen = function () {
console.log('[open] Connection established');
socket.send('New client');
};
// Log errors
socket.onerror = function (error) {
console.log('WebSocket Error ' error);
};
// Log messages from the server
socket.onmessage = function (e) {
console.log('Server: ' e.data);
};
socket.onclose = function(event) {
if (event.wasClean) {
alert(`[close] Connection closed cleanly, code=${event.code}
reason=${event.reason}`);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
alert('[close] Connection died');
}
};
function toServer(data) {
if(!isOpen(socket)) {
console.log('error,socket is closed');
return;
} else {
socket.send(data);
console.log(`data sent to server`);
};
};
//test
function snapshot() {
//take snapshot and...
//...send image to server
toServer(data);
};
Кто-нибудь знает, что происходит не так между связью клиент — > сервер?
Как я могу проверить, связана ли проблема с клиентом или сервером?
Мой сервер настроен неправильно или это мой клиент?
С уважением, Формирователь Горчицы