Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Express和WebSocket在同一端口上侦听_Javascript_Node.js_Websocket - Fatal编程技术网

Javascript Express和WebSocket在同一端口上侦听

Javascript Express和WebSocket在同一端口上侦听,javascript,node.js,websocket,Javascript,Node.js,Websocket,我有一个app.js,用于在收到一些POST数据时触发两个事件: 将POST数据插入数据库 使用WebSocket向客户端发送消息 这是app.js的应用程序(只有重要的行) 下面是server.js(仅重要行) 我想要实现的是将WebSocketServer设置为侦听应用程序的同一端口。 我考虑将服务器变量从app.js传递到server.js,但是 我认为这不是一种优雅的方式 我不知道怎么做 你们觉得怎么样 根据您的代码和注释,下面是一个超级简单的示例,说明它如何协同工作 首先,http s

我有一个app.js,用于在收到一些POST数据时触发两个事件:

  • 将POST数据插入数据库
  • 使用WebSocket向客户端发送消息
  • 这是app.js的应用程序(只有重要的行)

    下面是server.js(仅重要行)

    我想要实现的是将WebSocketServer设置为侦听应用程序的同一端口。 我考虑将服务器变量从app.js传递到server.js,但是

  • 我认为这不是一种优雅的方式
  • 我不知道怎么做

  • 你们觉得怎么样

    根据您的代码和注释,下面是一个超级简单的示例,说明它如何协同工作

    首先,http server.js
    -一个典型的express应用程序,除了我们不使用app.listen()启动服务器之外:

    现在是
    ws-server.js
    示例,其中我们从节点本地
    http.createServer()
    创建WSS服务器。现在,请注意,这就是我们导入应用程序的地方,并为这个原生http.createServer提供要使用的应用程序实例

    使用
    PORT=8080节点ws-server.js启动应用程序

    注意您正在启动第二个与套接字相关的文件(ws-server),而不是第一个与http相关的文件(http-server)。)

    最后,此示例通过创建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 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>
    
    
    WS示例
    套接字消息响应:
    
    留言回复: //这里非常简单,没有错误处理或任何东西 document.body.onload=函数(){ "严格使用",; //首先是套接字请求 函数socketExample(){ log('creatingsocket'); 让socket=newwebsocket('ws://localhost:8080/'); socket.onopen=函数(){ console.log(“套接字打开”); send(JSON.stringify({message:'生命、宇宙和一切的意义是什么?'); console.log('消息已发送') }; socket.onmessage=函数(消息){ 日志('套接字服务器消息',消息); 让data=JSON.parse(message.data); document.getElementById('response').innerHTML=JSON.stringify(数据,null,2); }; } //现在是简单的后期演示 函数postExample(){ console.log('Creating regular POST message'); 获取(“/”,{ 方法:“post”, 标题:{ “内容类型”:“应用程序/json” }, body:JSON.stringify({message:'后生命、宇宙和一切的意义是什么?')) }) .then(response=>response.json()) .then(函数(数据){ log('POST response:',data); document.getElementById('post-response').innerHTML=JSON.stringify(数据,null,2); }) .catch(函数(错误){ 日志('请求失败',错误); }); } //都叫他们; socketExample(); postExample(); }
    请注意,您需要一个非常新的浏览器,一个既有WebSocket又有用于客户端部分的fetch API的浏览器,但无论如何,它都是无关的,它只提供了它的要点。

    http和ws在同一端口80上,“惊人的Zlatko方法”™." 您将有一个文件,比如main.js,带有

     var app = express()
    
    还有许多行快速代码

    以通常的方式使用尽可能多的中间件,而不做任何更改,这是完全可以的

    var app = express()
    app.use(session(session_options))
    app.use(passport.initialize())
    app.use(passport.session())
    app.use('/static', express.static('static'))
    // etc etc
    app.get ...
    app.get ...
    app.post ...
    app.post ...
    
    通常在该文件的末尾

     app.listen(80, (err) => { ... })
    
    删除那个

     //app.listen(80, (err) => { ... })
    
    express应用程序文件中没有其他更改

    在您的websocket文件中,比如multiplayer.js,您通常会

    const WebSocket = require('ws');
    const wss = new WebSocket.Server({
        port: 9999,
        perMessageDeflate: false
    })
    
    事实上,改变为

    const WebSocket = require('ws');
    /*const wss = new WebSocket.Server({
        port: 2828,
        perMessageDeflate: false
    });*/
    let WSServer = WebSocket.Server;
    let server = require('http').createServer();
    let app = require('./main'); // note, that's your main.js file above
    let wss = new WSServer({
      server: server,
      perMessageDeflate: false
    })
    server.on('request', app);
    
    在文件的末尾

    server.listen(80, function() {
        console.log(`Amazing Zlatko Method™ combo server on 80`);
    });
    
    注意!-启动“multiplayer.js”文件(而不是“main.js”)


    它工作得很好。真是太棒了。

    你跳过了几行。你没有在express app上安装websocket服务器?哦,回答你的问题。这是通常的方式,为什么它不优雅?需要(某物);myServer.mount(某物);模块与其他模块一样。我确实没有在express应用程序上安装WebSocketServer,因为我不知道如何安装。请您提供一个示例,好吗?谢谢您的帮助!哇@Zlatko,这是一个非常好的答案。非常感谢您为我花费的时间。非常感谢!工作非常完美。@Zlatko无法设置几乎相等的使用nodejs“net”而不是“ws”的ent。net.createServer不会像实例化新的ws实例那样获取http服务器的实例-new WSServer({server:server})@DKebler这里的答案是针对
    express.js
    ws
    模块的,正如问题中所述。你是否试图将
    net
    侦听器包装在express周围?目的是什么,具体是什么?你有一个与问题相关的问题吗?嗯,我不认为它会失败得很惨。首先,请求url指的是一个相对路径,因为你在从同一来源(本例中为localhost:8080)删除文件,帖子也会在那里发布。websocket也会在那里连接。对于两个人来说,这是stackoverflow,解决方案不是字面意义上的,只是作为概念的证明。它会的。我真诚地希望你不要盲目地将代码从这里复制到你的工作中,而不阅读它,理解它,然后修改你的代码hree,是的,你肯定会使用反向代理。你担心的太多了;)我意识到我可以解决我的用例的方法是使用webpack dev中间件作为快速中间件,然后我不是添加webpack热中间件,而是通过compiler.hooks.afterEmit订阅webpack编译器事件,然后通过现有的自定义网站传递消息ocket服务器。这个安装程序也支持http吗?嗨@LenJoseph-是的,100%,这就是重点!我在“server.on”部分失败了(
     //app.listen(80, (err) => { ... })
    
    const WebSocket = require('ws');
    const wss = new WebSocket.Server({
        port: 9999,
        perMessageDeflate: false
    })
    
    const WebSocket = require('ws');
    /*const wss = new WebSocket.Server({
        port: 2828,
        perMessageDeflate: false
    });*/
    let WSServer = WebSocket.Server;
    let server = require('http').createServer();
    let app = require('./main'); // note, that's your main.js file above
    let wss = new WSServer({
      server: server,
      perMessageDeflate: false
    })
    server.on('request', app);
    
    server.listen(80, function() {
        console.log(`Amazing Zlatko Method™ combo server on 80`);
    });