Socket.io发出一次后连续显示消息

时间:2018-08-08 10:47:17

标签: node.js socket.io

Socket.io仅在一次发出时不断显示消息,除非重新加载页面,否则不会显示发出的消息。

这是发出消息的代码:

io.sockets.on('connection', function (socket) {
   console.log('A client is connected!');
   socket.emit('notification.'+notification.recipient, {message: 'A user just registered under your referral.'});
});

但是,当上述内容触发时,“客户端已连接!”仅记录一次,但是在前端它会连续显示,直到我不得不退出服务器为止。

这是前端代码:

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io();

    socket.on("newNotification."+current_user, function(event) {
    console.log("Message Emited: ", event.message)

    }.bind(this));
</script>

已更新

这是连接代码:

在app.js中

const createError = require('http-errors'),
express = require('express'),
logger = require('morgan'),
helmet = require('helmet'),
expressSanitizer = require('express-sanitizer'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
session = require('express-session'),
RedisStore = require("connect-redis")(session),
redis = require("redis").createClient(),
redisClient = require('redis').createClient({host : 'localhost', port : 6379})
path = require('path')

const app = express();

app.io = require('socket.io')();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.set('trust proxy', 1); // trust first proxy
app.use(logger('combined'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));
var sess = {
  key: 'user_sid',
  secret: 'TicTac Toe - Secret',
  saveUninitialized: true,
  resave: true,
  httpOnly: true,
  cookie: { maxAge: 1200000 },
  store: new RedisStore({ host: 'localhost', port: 6379, client: redis })
};
app.use(flash());
app.use(expressSanitizer());

app.use(express.static(path.join(__dirname, 'public/src')));
if (app.get('env') === 'production') {
  app.set('trust proxy', 1) // trust first proxy
  sess.cookie.secure = true // serve secure cookies
}

app.use(session(sess))

app.use('', require('./routes')(app.io));

// catch 404 and forward to error handler
app.use((req, res, next) => {
  next(createError(404))
});


module.exports = app;

这是bin / www代码:

#!/usr/bin/env node

require('dotenv').load();
var app = require('../app');
var debug = require('debug')('crypto-palace:server');
var http = require('http');

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);


var server = http.createServer(app);


server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

app.io.listen(server); 


function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {

    return val;
  }

  if (port >= 0) {
    return port;
  }

  return false;
}

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}


function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

谢谢。

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。

此解决方案在这里:

io.sockets.on('connection', function (socket) {
   console.log('A client is connected!');
   socket.emit('notification.'+notification.recipient, {message: 'A user just registered under your referral.'});
});

它发出一次并根据连接数多次显示消息。

所以这样做的权利是:

io.sockets.emit('notification.'+notification.recipient, {message: 'A user just registered under your referral.'});

这解决了它。