我使用express 4与socket.io。
当服务器运行时,套接字不起作用。
控制台无法打印'用户连接'。
客户端按钮不起作用。
请帮帮我。 : - (
这是我的代码
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', 'jade');
// 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.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
// 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;
io.js
var io = require('socket.io')();
io.on('connection', function(socket) {
console.log('user connected');
socket.on('rint', function(data) {
console.log('user send data : ' + data);
socket.emit('smart', data);
});
});
module.exports = io;
/ bin中/万维网
\#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var io = require('../io');
var debug = require('debug')('socketT:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
io.attach(server);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
...
的index.html
<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
window.onload = function() {
var socket = io();
socket.on('smart', function(data) {
alert(data);
});
document.getElementById('button').onclick = function() {
var text = document.getElementById('text').value;
socket.emit('rint', text);
});
});
</script>
</head>
<body>
<input type="text" id="text" />
<input type="button" id="button" value="echo" />
</body>
</html>
答案 0 :(得分:0)
您在服务器端的所有内容的监听器都已启用(“连接”,...但您不会在客户端的任何位置建立该连接。
请查看以下页面:http://socket.io/docs/
您需要添加要连接的服务器的URL:
的index.html:
var socket = io("localhost:8080"); //Or whatever your url and port are.