0

Just started to learn node.js for multiplayer capabilities:

Using windows 7, npm to install node.js and components I had few issues which were making me mad

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

was throwing error:

D:\projects\node\chat\index.js:3 var io = require('socket.io').(http); ^ SyntaxError: Unexpected token ( at Module._compile (module.js:439:25) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:901:3 

some time more wiered unable to handle or no such method defined, etc.

On client side in the browser following script was not working

<script> var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> 

was throwing (not error) but message for each action you perform in web:

debug - served static content /socket.io.js 

After doing lot of effort I come to two easy fixes shared in answer

2 Answers 2

2

I may be off base here, as I'm still learning node myself, but it appears to me the answer is more simple than the currently accepted (on 2014.7.21) suggests; you shouldn't have a . between require('socket.io') and (http); That would suggest it was some kind of anonymous function within the object returned by the require when it is actually the constructor that needs to be called.

It should look like this:

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

I am not sure on the resolution to your second problem, as I did not encounter it. But I did find that I needed to encapsulate the jquery functions inside a .ready() which is standard practice. The result looks like this:

var socket = io(); $(function () { socket.on('chat message', function (msg) { $('#messages').append($('<li>').text(msg)); }); $('#chatForm').submit(function () { socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); }); 
Sign up to request clarification or add additional context in comments.

Comments

0

For first error you will have to use listen method of socket.io, otherwise it don't work ( while I was following this according to socket.io chat example )

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

the second prompt or problem, which suppose to be working but somehow you must have to define url in io.connect method

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.