【发布时间】:2016-01-27 16:06:27
【问题描述】:
我有以下js代码
`var express = require('express');
var app = express();
var http = require('http').Server(app);
var path = require("path");
var io = require('socket.io')(http);
app.get('*', function (req, res){
res.sendFile(path.join(__dirname, '/Public'));
});
app.use('/home',express.static(path.join(__dirname,'/Public')));
//app.use('/static', express.static(__dirname + 'index.html'));
io.on('connection', function (socket) {
socket.on('message', function (data) {
socket.emit('news', { hello: 'world' });
});
socket.on('another-message', function (data) {
socket.emit('not-news', { hello: 'world' });
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});`
我有 HTML 代码
<html>
<h1>working</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000', { path :'/' +home});
socket.on('connect',function(){
socket.emit('message', 'Hello server');
});
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
<body>
<p>display a message</p>
</body>
</html>`
我转到页面 localhost:3000/home 并获得我的 HTML 页面。但是在控制台中我看不到任何消息。我哪里错了?请纠正我。
【问题讨论】:
-
请在 html socket.emit('message',{ 'msg' :'Hello server'});而不是 socket.emit('message', 'Hello server');
-
你得到什么错误?
-
@abhyudit 我没有收到任何错误,但没有在浏览器和节点之间传递任何消息。因此控制台和浏览器都是空的
-
您是否检查了浏览器控制台和终端(运行服务器的位置)是否有错误?如果没有发布错误,那么就会有其他内容。
标签: javascript node.js sockets socket.io