简体   繁体   English

Nodejs和socket.io服务器端口冲突

[英]Nodejs and socket.io server port conflict

I have NodeJS app (which also serves the client), and I'm trying to implement real time communication between the client and the server, so I'm using socket.io for this.我有 NodeJS 应用程序(它也为客户端提供服务),我正在尝试实现客户端和服务器之间的实时通信,所以我为此使用了 socket.io。

I added the following code in my server.js file:我在 server.js 文件中添加了以下代码:

const app = express();

const server = http.createServer(app);
realtime.connect(server);
server.listen(3002, () => {
  console.log(`Listening on port 3002`)
});

but whenever I'm changing my nodejs code, the server crash:但是每当我更改 nodejs 代码时,服务器就会崩溃:

Error: listen EADDRINUSE: address already in use :::3002

How I can fix this and avoid reloading the listen code of my socket.io server when browsersync reload my nodejs app?当 browsersync 重新加载我的 nodejs 应用程序时,如何解决这个问题并避免重新加载我的 socket.io 服务器的监听代码?

You can run the socket server in a separate port.您可以在单独的端口中运行套接字服务器。 And also you can use separate functions as middleware for the authentication.您还可以使用单独的功能作为身份验证的中间件。

Here is a simple example这是一个简单的例子

> index.js > 索引.js

import express from 'express';
import Socket from './socket';

const app = express();
const port = process.env.PORT || 3000;
const socketPort = process.env.SOCKET_PORT || 8001;
const io = require('socket.io')(socketPort);

// User Authentication
// app.use(verifyToken);

// Socket Authentication
// io.use(socketTokenVerification);
    
const socket = new Socket(io);
socket.modelLoaded();

app.listen(port, () => {
  log.info(`HTTP server is running 🚀 on port ${port}
Socket service running 🚀 on port ${socketPort}
Process Pid: ${process.pid}`);
});

> socket.js > 套接字.js

export default class {
  constructor(io) {
    this.io = io;
    this.connections = {};  // should be updated on connect and disconnect
  }

  addConnection(socket) {
    // your code here
  }

  removeConnection(socket) {
    // your code here
  }

  socketDisconnect(socket) {
    // your code here
  }

  modelLoaded() {
    const { io, connections } = this;
    io.on('connection', socket => {
      addConnection(socket);
      // any code here
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM