简体   繁体   中英

Node.js simplest code not working

As I am a newbie to Node.js and is learning from different articles. So, far I have learnt, my code is

At server side with 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);

At client side with 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>

What is that I am doing wrong in above code? When I run app.js in console, it says info - socket.io started but when I run http://localhost:3000 it just keep requesting server.

plus I want to know that is it true that wherever on my pc I create my folder for Node and place app.js and index.html files like above in it and run http://localhost:3000 in browser will automatically make that folder my site folder for localhost after running app.js in Node console?

In your app.js update code to this

 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
 });

Hope that solves your problem

You're not supposed to do this on server side:

socket.emit('connect',{msg:'Hello Client'});

because connect is a default event which is emitted on a successful connection from the server. So when a client connects, the server fires its default 'connect' event, but here you're also triggering your event named connect which might be causing problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM