expressjs和socket.io - 在客户端上复制消息

时间:2016-03-27 22:11:34

标签: node.js express socket.io

我是Node的初学者,我正在尝试使用socket.io构建聊天功能。问题是:我的客户端(浏览器)在事件被触发时收到两条消息。

app.js
var express = require('express');   
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exload = require('express-load');
var exSession = require('express-session');
var methodOverride = require('method-override');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(cookieParser('ntalk'));
app.use(exSession({
  secret: 'sandman',
  resave: false,
  saveUninitialized: true
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')));

exload('models')
.then('controllers')
.then('routes')
.into(app);

module.exports = app;
//bin/www
#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('express4:server');
var http = require('http');
var server = require('http').Server(app);
var io = require('socket.io')(server);

/**
 * Configuring socket.io
 */
io.sockets.on('connection', function(client) {
    client.on('send-server', function(data) {
        var msg = "<b>" + data.name + ":</b>" + data.msg + "<br>";
        client.emit('send-client', msg);
        client.broadcast.emit('send-client', msg);
    })
});

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


server.listen(port);
//page-script.jade
script.
    var socket = io('http://localhost:3000');
        socket.on('send-client', function(msg){
            document.getElementById('chat').innerHTML += msg;
    })

    var send = function(event) {
        var nome = document.getElementById('name').value;
        var msg = document.getElementById('msg').value;

        socket.emit('send-server', {name : name, msg : msg});
    }

聊天会发生什么: http://imgur.com/rVBx19l

我知道文件有一些不好的实践,一旦我做对了,我就会重构这个:)

1 个答案:

答案 0 :(得分:1)

我知道,这则帖子很旧。但没有结论。供将来参考。

重复项来自这里:

这行代码: client.emit('send-client', msg); 向所有套接字(包括您自己)发出数据“ msg”。

这行代码: client.broadcast.emit('send-client', msg); 广播数据到所有连接到套接字的人,排除自己。

这就是为什么套接字有2个响应的原因。