如何在ExpressJS中连接socket.io

时间:2016-02-01 14:52:58

标签: node.js sockets

早上好,为什么这段代码无法正常工作(服务器响应,但" io.on" no):

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

//this code not work in console // even it can not see
io.on('connection', function(socket) {
        console.log('a user connect');
        socket.on('disconnect', function() {
            console.log('a user disconnect');
        });
    });

//server respond
http.listen(3000, function() {
        console.log('Server running at 3000');
    });

我是npm

下载的初学者,express和socket.io

1 个答案:

答案 0 :(得分:0)

您需要一台服务器以及一台与socket io服务器建立连接的客户端。

根据我从您的代码中理解的内容,我想你想做这样的事情:

首先是你的server.js:

#!/usr/bin/env node
var http = require('http');
var express = require('express');
var app = express();
var io = require('socket.io');

var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);

var socketio = io.listen(server);

setInterval(function() {
    console.log("Emitting..");
    socketio.emit('data', {"x":"123"}); 
}, 2000);

module.exports = app;

然后你的client.html :(我正在编写一个客户端,它将登录浏览器控制台。)

<html>
<head></head>
<body>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect("http://localhost:3000/");

    socket.on('connect', function() {
        console.log('connected');
    });

    socket.on('disconnect', function(){
       console.log('disconnected');
    });

    socket.on("data", function(data) {
        console.log(data);
    });
</script>
</body>

那就是它。现在使用node server.js启动服务器,然后在浏览器中打开client.html并检查控制台。如果有任何不清楚的地方,请告诉我。