因为我是Node.js的新手,所以我正在学习不同的文章。所以,据我所知,我的代码是
在服务器端使用app.js
var http = require('http');
var app = http.createServer(function(req,res)
{
req.on('end',function()
{
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello');
});
});
var io = require('socket.io').listen(app);
io.sockets.on('connection',function(socket)
{
socket.emit('connect',{msg:'Hello Client'});
socket.on('client_Says',console.log);
});
app.listen(3000);在客户端使用index.html
<script type="text/javascript" src="//localhost:3000/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('//localhost:3000');
socket.on('connect',function(data)
{
alert('Server says '+data.msg);
socket.emit('client_Says',{data:'Hello Server'});
});
</script>我在上面的代码中做错了什么?当我在控制台中运行app.js时,它说info - socket.io启动了,但是当我运行http://localhost:3000时,它只是不断地请求服务器。
另外,我想知道,在我的pc上,我在任何地方为节点创建我的文件夹,并将、app.js、和index.html文件放在其中,并在浏览器中运行http://localhost:3000,在节点控制台中运行app.js之后,会自动将该文件夹作为本地主机的站点文件夹吗?
发布于 2014-01-28 13:13:14
在您的app.js更新代码中
var http = require('http'),
fs = require('fs'), //<--- File Module
index = fs.readFileSync(__dirname + '/index.html');
var app = http.createServer(function(req,res)
{
res.writeHead(200, {'Content-Type': 'text/html'}); //<-Updated to text/html
res.end(index); //<---I am sending page
});希望这能解决你的问题
发布于 2014-01-29 05:40:25
您不应该在服务器端这样做:
socket.emit('connect',{msg:'Hello Client'});因为connect是一个默认事件,它是在服务器成功连接上发出的。因此,当客户端连接时,服务器会触发默认的“connect”事件,但在这里您也会触发名为connect的事件,这可能会导致问题。
https://stackoverflow.com/questions/21406055
复制相似问题