根据您的代码和 cmets,这是一个超级简单的示例,说明它如何协同工作。
首先,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's 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 示例,我们从节点本机 http.createServer() 创建 WSS 服务器。现在,请注意这是我们导入应用程序的地方,并为这个原生 http.createServer 提供应用程序实例以使用。
使用PORT=8080 node ws-server.js 启动应用程序:
(注意您正在启动第二个,套接字相关的文件(ws-server)而不是第一个,http 相关的文件(http-server)。)
'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 和 fetch API,但无论如何这无关紧要,它只是为您提供了它的要点。