用于浏览器客户端和node.js客户端的express,socket.io服务器

时间:2015-07-30 01:03:11

标签: node.js express socket.io

我正在尝试使用socket.io设置一个Express服务器,它允许node.js客户端和浏览器客户端连接。浏览器连接没有问题。使用socket.io-client的node.js客户端给出错误: unhandled socket.io url

服务器:

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

var app = express();
var host = 'localhost';
var port = process.env.PORT || 8080;

var server = app.listen(port, function() {
    console.log('Gulp is starting my app on PORT: ' + port)
});
io = io.listen(server);

app.use('/', express.static(__dirname + '/'));

io.on("connection", function(socket) {

    socket.on('clientMessage', function(jsonData, from) {
        socket.emit('serverMessage', 'Got a message!');
        console.log('Data being sent from', from, 'is:\n' + jsonData);
    });
});

客户端:

var io = require('socket.io-client')

var socket = io.connect('http://192.168.1.222:8080', {reconnect: true});

socket.emit('clientMessage', 'Hello', 'Pi-Voyager');

1 个答案:

答案 0 :(得分:0)

问题在于我要求我的依赖关系。它适用于其他版本,但在我目前的版本上没有。

node -v
v0.12.4

"express": "^4.13.1",
"socket.io": "^1.3.6",
"socket.io-client": "^1.3.6"

使用这些版本,以下代码可以正常工作:

服务器

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

var port = process.env.PORT || 8080;

server.listen(port, function() {
    console.log('Gulp is starting my app on PORT: ' + port)
});

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

io.on("connection", function(socket) {

    socket.on('clientMessage', function(jsonData, from) {
        socket.emit('serverMessage', 'Got a message!');
        console.log('Data being sent from', from, 'is:\n' + jsonData);
    });

});

客户端

var io = require('socket.io-client')

var socket = io.connect('http://10.1.0.47:8080', {reconnect: true});

socket.emit('clientMessage', 'Hello', 'Pi-Voyager');