我使用node.js和socket.io进行以下设置:
客户:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>No title</title>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<body>
<script>
var socket = io();
socket.on('init', function() {
console.log('Hello world !');
})
</script>
</body>
</html>
服务器:
const https = require('https');
var port = 80,
http = require('http'),
app = require('express')(),
server = require('http').Server(app),
io = require('socket.io')(server),
CronJob = require('cron').CronJob,
fs = require('fs');
// ...
io.on('connection', function(client) {
console.log('User connected.');
client.emit('init');
client.on('disconnect', function () {
console.log('User disconnected.');
});
});
您是否知道为什么我的服务器或浏览器日志中没有任何消息(除了用户连接。&#39;和用户已断开连接。&#39;) ?我想这是微不足道的,但我无法找到......
谢谢!
编辑:
我补充说:
客户:
socket.emit('hello');
服务器:
io.on('hello', function() {
console.log('Hello world !');
});
它也不起作用......
编辑2:
server.listen(port);
register('Express', 'Listening on port', port);
app.get( '/', function( req, res ){
res.sendFile( root + '/index.html' );
});
app.get( '/*', function(req, res, next) {
var file = req.params[0];
register('File requested', file);
res.sendFile( root + '/' + file );
});