代码之家  ›  专栏  ›  技术社区  ›  Max Wolfen

无法用socket.io启动nodejs服务器

  •  0
  • Max Wolfen  · 技术社区  · 6 年前

    所以,我有一个简单的梦想,用socket.io库启动服务器,但是由于某些原因,它没有发生……我无法理解什么是错误的,因为在服务器运行时我甚至没有收到标准消息- Server running on port ${port} .

    救命,求你了…

    'use strict'
    
    const express = require('express');
    const http = require('http');
    const io = require('socket.io');
    const mongoose = require('mongoose');
    const bodyParser = require('body-parser');
    const cookieParser = require('cookie-parser');
    const bcrypt = require('bcrypt-nodejs');
    const session = require('express-session');
    const MongoStore = require('connect-mongo')(session);
    
    const app = express();
    const server = http.Server(app);
    const socketServer = io(server);
    const router = express.Router();
    
    const chat = require('./routes/chat');
    const profile = require('./routes/profile');
    const registration = require('./routes/registration');
    const login = require('./routes/login');
    const logout = require('./routes/logout');
    
    const EmployersSchemaDB = require('./SchemaDB/EmployersSchemaDB');
    const MessagesSchemaDB = require('./SchemaDB/MessagesSchemaDB');
    const User = require('./SchemaDB/ShemaAuthtificaion');
    
    mongoose.connect('mongodb://test_db');
    
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(cookieParser());
    
    app.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
        res.setHeader('Access-Control-Allow-Credentials', 'true');
        res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
        res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
        res.setHeader('Cache-Control', 'no-cache');
        next();
    });
    
    app.use(session({
        secret: 'work hard',
        resave: true,
        saveUninitialized: false,
        store: new MongoStore({ mongooseConnection: mongoose.connection })
    }));
    
    router.route('/')
        .get((req, res) => {
        res.json('Hello on the Homepage!');
    });
    
    app.use('/', router);
    app.use('/chat', chat);
    app.use('/profile', profile);
    app.use('/auth/login', login);
    app.use('/auth/logout', logout);
    app.use('/auth/registration', registration);
    
    const port = process.env.API_PORT || 8989;
    socketServer.listen(port, () => {
        console.log(`Server running on port ${port}`);
    });
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   jfriend00    6 年前

    从此处更改:

    socketServer.listen(port, () => {
        console.log(`Server running on port ${port}`);
    });
    

    为此:

    server.listen(port, () => {
        console.log(`Server running on port ${port}`);
    });
    

    您需要启动HTTP服务器。这是这里的核心服务器,它同时处理express和socket.io,并将所有传入的请求字段化。

    你的变量 socketServer 还有你的 io 变量的名称有误(这可能是混淆的一部分)。 插座服务器 是实际的服务器,即socket.io服务器端实例,通常命名为 输入输出 . 见 the socket.io server doc 有关详细信息。

        2
  •  2
  •   desoares    6 年前

    您应该从一个更简单的服务器开始:

    const express = require('express');
    const socketio = require('socket.io');
    const http = require('http');
    const app = express();
    const server = http.createServer(app);
    const socket = socketio(server);
    
    app.use(express.static(`./public`));
    
    socket.on('connect', socket => {
      socket.emit('identify', {'server':'server data'});
    });
    
    socket.on('data', data => {
      console.log(data);
    });
    
    server.listen(4000, () => {
      console.log('Server up and running on port 4000');
    });
    

    在前端,您可以这样测试:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Test</title>
      </head>
      <body>test
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
        <script type="text/javascript">
          'use strict';
          var socket = io('http://localhost:4000');
    
          socket.on('identify', function (socket) {
            console.log(socket);
          });
        </script> 
      </body>
    </html>