我想实现与客户端的简单socket.io连接。为此,我使用nodeJS with express。
我的客户档案如下:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js" />
<!--<script src="http://fb.me/react-0.12.2.min.js"></script>-->
<script src='/javascripts/socket.js'></script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %> Juhu!</p>
</body>
</html>
socket.js
/**
* socket io connection
*/
var socket = io.connect("http://localhost:3000");
我的服务器网站看起来像这样:
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 routes = require('./routes/index');
//var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
//app.use('/users', users);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
www.js
#!/usr/bin/env node
var debug = require('debug')('Test');
var app = require('../app');
var Pusher = require('pusher-client');
var http = require('http');
app.set('port', process.env.PORT || 3000);
//Create the HTTP server with the express app as an argument
var server = http.createServer(app);
/*var server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});*/
/**
* return pusher data
*/
var API_KEY = 'cb65d0a7a72cd94adf1f';
var pusher = new Pusher(API_KEY, {
encrypted: true
});
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function (data) {
//console.log(data);
});
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
var stream = channel.bind("message", function (data) {
//console.log(data);
});
io.sockets.on("connection", function (socket) {
// The user it's added to the array if it doesn't exist
if(users.indexOf(socket.id) === -1) {
users.push(socket.id);
}
// Log
logConnectedUsers();
/*// This is a listener to the signal "something"
stream.on("start stream", function (data) {
console.log("Test: ", data);
socket.emit('info', { data: data });
});*/
// This handles when a user is disconnected
socket.on("disconnect", function(o) {
// find the user in the array
var index = users.indexOf(socket.id);
if(index != -1) {
// Eliminates the user from the array
users.splice(index, 1);
}
logConnectedUsers();
});
});
// A log function for debugging purposes
function logConnectedUsers() {
console.log("============= CONNECTED USERS ==============");
console.log("== :: " + users.length);
console.log("============================================");
}
//server listens
server.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});
我希望在打开浏览器时,至少会收到一条消息,说明在nodejs app中连接了一个新客户端。但是,我一无所获。
任何建议我做错了什么?
更新
我更改了以下代码,但是我仍然没有连接:
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
var stream = channel.bind("message", function (data) {
//console.log(data);
});
io.on("connection", function (socket) {
// The user it's added to the array if it doesn't exist
if(users.indexOf(socket.id) === -1) {
users.push(socket.id);
}
// Log
logConnectedUsers();
socket.emit('someevent', { attr: 'value' } )
/*// This is a listener to the signal "something"
stream.on("start stream", function (data) {
console.log("Test: ", data);
socket.emit('info', { data: data });
});*/
// This handles when a user is disconnected
socket.on("disconnect", function(o) {
// find the user in the array
var index = users.indexOf(socket.id);
if(index != -1) {
// Eliminates the user from the array
users.splice(index, 1);
}
logConnectedUsers();
});
});
这s all of my console output, when calling
本地主机:3000`
Wed, 31 Dec 2014 11:24:00 GMT Test Express server listening on port 3000
GET / 304 19.798 ms - -
GET /stylesheets/style.css 304 15.385 ms - -
更新
我的index.js路由文件:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
更新
我现在从我页面末尾的客户端加载我的socket.js脚本,并收到以下错误消息:
GET http://localhost:3000/socket.io/1/?t=1420027015782 400
(Bad Request)socket.io.min.js:2 d.handshakesocket.io.min.js:2 d.connectsocket.io.min.js:2 dsocket.io.min.js:2 c.connectsocket.js:4 (anonymous function)
答案 0 :(得分:2)
到目前为止,您所拥有的(严格来说)是客户端连接到服务器。 (html + socket.js调用io.connect()
)。
也许你问的是从服务器向客户端发送数据? 在pherris的功能中,您可以使用
将数据发送到客户端io.on('connection', function (socket) {
console.log('a user connected')
socket.emit('someevent', { attr: 'value' } )
})
并再次使用
在客户端捕获它var socket = io.connect("http://localhost:3000");
socket.on('someevent', function (data) { console.log(data) })
然后向服务器发送另一个事件。 沟通可以两种方式完成。取决于您的需求。