SocketIO阻止服务器

时间:2018-11-27 08:56:30

标签: express socket.io

我有一个简单的应用程序,该应用程序使用express服务来创建创建套接字连接的静态页面。问题是服务器在一两分钟后停止响应。这是代码:

server.js

const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');  
const publicPath = path.join(__dirname, './public');

const port = 3000;

  let app = express();
  let server = http.createServer(app);
  var io = socketIO(server);

  app.get(`/`, (req, res) => {
    res.sendFile(publicPath + '/index.html');
  });

  server.listen(port, () => {
    console.log('listening...');
  })

  io.on('connection', (socket) => {
   socket.on('test', (data) => {
    console.log(data);
   });
  });

index.html

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  </head>

  <body class="centered">
    <center><h1>This is a test</h1></center>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
      socket.on('connect', () => {
        socket.emit('test', 'this is some data');
      });
    </script>

  </body>

</html>

Package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.4",
    "socket.io": "^2.1.1"
  }
}

当然在服务器或客户端上没有错误。如果我删除了var socket = io()行,则该应用程序将顺利运行。

0 个答案:

没有答案