unoomad
unoomad

Reputation: 85

connection refused node js

Helle every body i desired to test sockets,when i'm connected a alert should appear, it work on the computer where Node js is in installed but not in the other computer.

The error :

Failed to load resource: net::ERR_CONNECTION_REFUSED http://xxx.xxx.xxx.xxx:8080/socket.io/socket.io.js Uncaught ReferenceError: io is not defined

the code : server:

var http = require('http');
var fs   = require('fs');
var io = require('socket.io');

var server = http.createServer(function(req,res){
    res.writeHead(200,{'Content-Type' : 'text/html'});
    fs.readFile('./index.html',function(err,content){
        res.end(content);
    });

}).listen(8080);

io = io.listen(server)

io.sockets.on('connection',function(client){

client.emit('connecte');

});

client :

<html>
<meta charset='utf-8'/>
<head>
    <title>my first page</title>
<script src="http://localhost:8080/socket.io/socket.io.js" ></script>
</head>
<body>
    <h1>It work</h1>
</body>
<script>
var socket; 

socket = io.connect('http://localhost:8080');

socket.on('connecte', function(){
        alert('You are connected');
    });

</script>
</html>

sorry for the language english is not my first language i try to learn. Thanks

Upvotes: 1

Views: 8888

Answers (1)

mscdex
mscdex

Reputation: 106698

The Socket.IO docs shows how to use Socket.IO with the built-in http server. Comparing that example and your code you can see you're not using io quite right. Try something like this:

var http = require('http');
var fs = require('fs');
var io = require('socket.io');

var server = http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/html'});
  fs.readFile('./index.html', function(err, content) {
    res.end(content);
  });
});

io = io(server);

server.listen(8080);

io.on('connection', function(client) {
  client.emit('connected');
});

Also on an unrelated note, you could pipe() the html file to the client instead of buffering the entire file first:

  res.writeHead(200, {'Content-Type': 'text/html'});
  fs.createReadStream('index.html').pipe(res);

Upvotes: 1

Related Questions