0

I have been trying my hand at node.js and socket.io, and following a tutorial. I keep getting an error from an application i am building. This is my server.js file:

var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
var chatServer = require('./lib/chat_server.js');
chatServer.listen(server);

//file doesn't exist
function send404(response) {
    response.writeHead(404, {'Content-Type': 'text/plain'});
    response.write('Error 404: resource not found.');
    response.end();
}

//handles serving file data
function sendFile(response, filePath, fileContents) {
    response.writeHead(
    200,
    {"content-type": mime.lookup(path.basename(filePath))}
    );
    response.end(fileContents);
}

//cache static files to memory
function serveStatic(response, cache, absPath) {
    if (cache[absPath]) {
        sendFile(response, absPath, cache[absPath]);
    } else {
        fs.exists(absPath, function(exists) {
            if (exists) {
            fs.readFile(absPath, function(err, data) {
                if (err) {
                    send404(response);
                } 
                else {
                    cache[absPath] = data;
                    sendFile(response, absPath, data);
                }
            });
           } 
           else {
            send404(response);
           }
        });
    }
}

var server = http.createServer(function(request, response) {
    var filePath = false;
    if (request.url == '/') {
        filePath = 'public/index.html';
        } 
    else {
        filePath = 'public' + request.url;  
    }
    var absPath = './' + filePath;
    serveStatic(response, cache, absPath);
});

server.listen(3001, function() {
    console.log("Server listening on port 3001.");
});

This is my index.html file:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Chat</title>
    <meta name="description" content="An interactive chat application using websockets.">
    <link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
    <div id='content'>
        <div id='room'></div>
        <div id='room-list'></div>
        <div id='messages'></div>
        <form id='send-form'>
            <input id='send-message' />
            <input id='send-button' type='submit' value='Send'/>
            <div id='help'>
                Chat commands:
                <ul>
                    <li>Change nickname: <code>/nick [username]</code></li>
                    <li>Join/create room: <code>/join [room name]</code></li>
                </ul>
            </div>
        </form>
    </div>
    <script src="[localserver here]:3001/socket.io/socket.io.js" type="text/javascript"></script>
    <script src="/javascripts/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script src="/javascripts/chat.js" type="text/javascript"></script>
    <script src="/javascripts/chat_ui.js" type="text/javascript"></script>
</body>
</html>

Upon loading "[localserver here]:3001" from the browser, the index page appears with the ensuing CSS. But when i try an event, like sending a message, i get this error:

Error 404: resource not found.

I right-clicked and inspected element from my Chrome browser and got this two messages:

Failed to load resource: the server responded with a status of 404 (Not Found) "[localserver here]:3001/socket.io/socket.io.js"

Uncaught ReferenceError: io is not defined "[localserver here]:3001/javascripts/chat_ui.js:26"

This is line 26 from my chat_ui.js file:

var socket = io.connect('[localserver here]:3001');
$(document).ready(function() {

   var chatApp = new Chat(socket);
   socket.on('nameResult', function(result) {
       var message;
       if (result.success) {
           message = 'You are now known as ' + result.name + '.';
       } else {
           message = result.message;
       }
       $('#messages').append(divSystemContentElement(message));
   });

   socket.on('joinResult', function(result) {
       $('#room').text(result.room);
       $('#messages').append(divSystemContentElement('Room changed.'));
   });

   socket.on('message', function (message) {
       var newElement = $('<div></div>').text(message.text);
       $('#messages').append(newElement);
   });

   socket.on('rooms', function(rooms) {
       $('#room-list').empty();
       for(var room in rooms) {
           room = room.substring(1, room.length);
           if (room != '') {
               $('#room-list').append(divEscapedContentElement(room));
           }
       }
       $('#room-list div').click(function() {
           chatApp.processCommand('/join ' + $(this).text());
           $('#send-message').focus();
       });
   });

   setInterval(function() {
       socket.emit('rooms');
   }, 1000);
   $('#send-message').focus();
   $('#send-form').submit(function() {
       processUserInput(chatApp, socket);
       return false;
   });
})

I have tried all sorts. Initially line 26 was var socket = io.connect(); and i changed it to the one above. I also changed the directory of socket.io.js in the index.html file from:

to

...as i thought this was the problem, but it is still giving me the same error.

Please how do i resolve this?

(PS - I am using Brackets as my IDE for node.js development. Also, i used "[localserver]" to indicate the localhost)

Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
gbade_
  • 339
  • 1
  • 8
  • 21
  • Sorry, i changed the directory in my html file from /socket.io/socket.io.js to localhost:3001/socket.io/socket.io.js but i still get the same errors... – gbade_ Jun 05 '14 at 11:43

2 Answers2

4

Try this:

<script type="text/javascript" src='http://localhost:3001/socket.io/socket.io.js'>
</script>

<script type="text/javascript">

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

socket.on('connect',function(){
console.log("connect");
});
</script>

It must help you.

Edgar
  • 113
  • 1
  • 1
  • 7
  • I have tried what you suggested. I am still getting the same error. – gbade_ Jun 05 '14 at 13:13
  • Do you have socket.io package installed? Is your server running when you try to connect? – Edgar Jun 05 '14 at 13:20
  • yes, i have socket.io installed, particularly in my file directory. It is in the node_modules folder and when i run server.js, i get the message: "info: socket.io started Server listening on port 3001." in my console – gbade_ Jun 05 '14 at 13:27
  • Ok. Then try to move chatServer.listen(server); after server.listen(3001, function() { console.log("Server listening on port 3001."); }); in your server.js file. – Edgar Jun 05 '14 at 13:37
  • Or move this in the head tag in your index.html file. – Edgar Jun 05 '14 at 13:41
  • I tried just that and stopped having :"Failed to load resource: the server responded with a status of 404 (Not Found)" as an error. But i still have "Uncaught ReferenceError: io is not defined localhost:3001/javascripts/chat_ui.js:26" as an error. It still points to line 26. I have changed line 26 from var socket = io.connect(); to var socket = io.connect('http://localhost:3001'); and i'm still getting the same error. – gbade_ Jun 05 '14 at 14:08
  • Try to move all scripts in head. – Edgar Jun 05 '14 at 14:15
  • thanks. It's now working. Also had to comment out var socket = io.connect(); in the chat_ui.js file – gbade_ Jun 05 '14 at 15:00
0

The line chatServer.listen(server); should be after you run your server. chartServer is listening to the server but that one is not running yet.

Try to move this line:

chatServer.listen(server);

to the end of your script server.js

m02ph3u5
  • 3,022
  • 7
  • 38
  • 51