Ответ 1
Основываясь на вашем коде и комментариях, вот супер простой пример того, как он будет работать вместе.
Во-первых, http-server.js
- типичное экспресс-приложение, за исключением того, что мы не запускаем сервер с app.listen()
:
'use strict';
let fs = require('fs');
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
app.use(bodyParser.json());
// Let create the regular HTTP request and response
app.get('/', function(req, res) {
console.log('Get index');
fs.createReadStream('./index.html')
.pipe(res);
});
app.post('/', function(req, res) {
let message = req.body.message;
console.log('Regular POST message: ', message);
return res.json({
answer: 42
});
});
module.exports = app;
Теперь пример ws-server.js
, где мы создаем сервер WSS из node native http.createServer()
. Теперь обратите внимание, что здесь мы импортируем приложение и даем этому встроенному http.createServer экземпляр приложения для использования.
Запустите приложение с помощью PORT=8080 node ws-server.js
:
'use strict';
let WSServer = require('ws').Server;
let server = require('http').createServer();
let app = require('./http-server');
// Create web socket server on top of a regular http server
let wss = new WSServer({
server: server
});
// Also mount the app here
server.on('request', app);
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log(`received: ${message}`);
ws.send(JSON.stringify({
answer: 42
}));
});
});
server.listen(process.env.PORT, function() {
console.log(`http/ws server listening on ${process.env.PORT}`);
});
Наконец, этот пример index.html
будет работать, создав запрос POST и Socket и отобразит ответ:
<html>
<head>
<title>WS example</title>
</head>
<body>
<h2>Socket message response: </h2>
<pre id="response"></pre>
<hr/>
<h2>POST message response: </h2>
<pre id="post-response"></pre>
<script>
// Extremely simplified here, no error handling or anything
document.body.onload = function() {
'use strict';
// First the socket requesta
function socketExample() {
console.log('Creating socket');
let socket = new WebSocket('ws://localhost:8080/');
socket.onopen = function() {
console.log('Socket open.');
socket.send(JSON.stringify({message: 'What is the meaning of life, the universe and everything?'}));
console.log('Message sent.')
};
socket.onmessage = function(message) {
console.log('Socket server message', message);
let data = JSON.parse(message.data);
document.getElementById('response').innerHTML = JSON.stringify(data, null, 2);
};
}
// Now the simple POST demo
function postExample() {
console.log('Creating regular POST message');
fetch('/', {
method: 'post',
headers: {
"Content-type": "application/json"
},
body: JSON.stringify({message: 'What is the meaning of post-life, the universe and everything?'})
})
.then(response => response.json())
.then(function (data) {
console.log('POST response:', data);
document.getElementById('post-response').innerHTML = JSON.stringify(data, null, 2);
})
.catch(function (error) {
console.log('Request failed', error);
});
}
// Call them both;
socketExample();
postExample();
}
</script>
</body>
</html>
Обратите внимание, что вам понадобится совсем недавний браузер, в котором есть и WebSocket, и API-интерфейсы Fetch для этой части клиентской части, но это не имеет значения, это просто дает вам суть.