栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Express和WebSocket在同一端口上侦听

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Express和WebSocket在同一端口上侦听

根据您的代码和注释,这是一个如何一起工作的超简单示例。

首先,

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 responseapp.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

示例中,我们从一个native节点创建WSS服务器
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 serverlet wss = new WSServer({  server: server});// Also mount the app hereserver.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和套接字“请求”并显示响应来工作:

<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 anythingdocument.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,但是无论如何它都无关紧要,只是给您了要点。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/392362.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号