将socket.io与express结合使用

时间:2014-08-04 13:13:16

标签: node.js express socket.io

我正在尝试在用户连接和断开连接时发送基本消息。后来我想来回发送参数。但是使用以下代码时,我不会在连接/断开连接时将消息打印在服务器上。

当我用server.on替换io.on时,我可以收到消息' User connected'但是当我刷新/关闭页面时,用户不会断开连接。然而这是错误的,因为不是每次刷新它都会记录消息,并且在第一次有时会多次记录消息。

server.js

var //io      = require('socket.io'),
    http    = require('http'),
    express = require('express');

var PORT = process.env.PORT || 8080,
    HOST = process.env.HOST || 'localhost';

var app = express();
app.use(express.static(__dirname + '/views'));

app.get('/', function (req, res) {
    res.sendfile(__dirname + 'index.html');
});

server = http.Server(app);
//io = io.listen(server);
var io = require('socket.io')(server);

io.on('connection', function(socket){
    console.log('User connected');


    io.on('disconnect', function(socket) {
        console.log('User Disconnected');
    });
});


server.listen(PORT, HOST, null, function() {
    console.log('Server listening on port %d in %s mode', this.address().port, app.settings.env);
});

新代码:

var express = require('express'),
    app = express(),
    http = require('http'),
    server = http.createServer(app),
    io = require('socket.io').listen(server);


var PORT = process.env.PORT || 8080,
    HOST = process.env.HOST || 'localhost';


server.listen(PORT);

app.use(express.static(__dirname + '/views')); //need this for my directory structure.


app.get('/', function (req, res) {
    res.sendfile(__dirname + 'index.html');
}); //Need this to call my page.


io.on('connection', function( client ){
    console.log('Connected');//this does not work.


    io.on('disconnect', function( client) {
        console.log(client);
    });
});

2 个答案:

答案 0 :(得分:1)

尝试重新配置套接字和服务器实例化:

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(process.env.PORT || 3000);

io.on('connection', function( client ) {
    console.log(client) //this will now work

   client.on('disconnect', function( id ) { 
       console.log('user with ID ' + id + ' has disconnected');
   });
});

答案 1 :(得分:1)

首先,您需要确定是否已包含客户端socket.io文件。

<script src="/socket.io/socket.io.js"></script>

然后你需要初始化套接字连接。

<script>
 var socket = io();
 </script>

以上更改将在您的index.html文件中。

现在在server.js文件中,

io.sockets.on('connection', function(socket) {
    console.log("User connected");
   socket.on('disconnect', function() {
      console.log('Got disconnect!');

   });
});