socket.io connection via client not working - node.js

I have just started using node.js socket.io. I am working on a simple connection between client and server.
Here is my server code:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var socketio = require('socket.io');
var app = express();
app.set('port', process.env.PORT || 1337);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', routes.index);
var server = app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = socketio.listen(server);
and this is the client code(http://smartican.com/nodetest.html):
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="socket.io.js"></script>
<script type="text/javascript">
var socket;
socket = io.connect("http://smartican.com:1337/");
$(function() {
alert(socket.transport.sessionid);
});
</script>
</head>
</html>
there seems to be a problem when connecting to the socket from client as line
socket = io.connect("http://smartican.com:1337/");
breaks the script.. I have tested and the socket is open

Your socket.io.js is the wrong javascript file. It's the server javascript not the client javascript. You want socket.io-client.js. Take a look at this answer.

Related

Not able to connect Socket.io in express

I tried with a different solution to connect to the socket.io but I am not able to connect to it following is my code snippet.
app.js
var express = require('express');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use('/', index);
app.use('/users', users);
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log('Client connected.');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
index.jade
extends layout
script(src='/socket.io/socket.io.js')
script.
var socket = io();
Package.json after installing socket.io
"socket.io": "^2.0.3"
Please suggest me where I am doing wrong
Try with new key word, may be it will work
var app = new express();

socket.io server not listening to connection event (express server)

I've been banging my head against a couple of guides as well as their docs and it seems like I have everything right. I expect when I navigate to localhost:8080 that the connection event triggers and my console.log message should appear.
// modules =================================================
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io')(server),
bodyParser = require('body-parser'),
methodOverride = require('method-override')
;
// config files ============================================
var db = require('./config/db');
// configuration ===========================================
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
// routes =================================================
require('./app/routes')(app);
io.on('connection', function(){
console.log("Why won't this display anything");
});
// set port && listen
var port = process.env.PORT || 8080;
server.listen(port);
console.log('Server connected on port ' + port);
exports = module.exports = app;
To see a socket.io connection on the server, you need client-side code in your web page that creates the socket.io connection.
That would typically look like this:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
// do more things with the connection here
</script>

Socket.io Failed to load resource

i have error
Failed to load resource http://localhost:3250/socket.io/1/?t=1376856906369
when i try do something with socket.io (loading work properly)
it is my first lines server
var express = require('express')
, http = require('http')
, mysql = require('mysql');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8080);
app.set('view engine', 'swig');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/lib'));
You are starting the server on port 8080, but you are trying to get socket.io from port 3250. So you either need to change this line:
//server.listen(8080);
server.listen(3250);
...or you use "http://localhost:8080" or just "http://localhost" in your browser.

How to correctly set socket.io ports? Getting socket.io.js 404

I have the following setup, according to the documentation:
Client-side:
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect(); // TIP: .connect with no args does auto-discovery
Server-side:
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path');
app = express(),
server = http.createServer(app).listen(80),
io = require('socket.io').listen(server);
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
Why am I getting
GET http://localhost:5000/socket.io/socket.io.js 404 (Not Found)
I tried switching to server = http.createServer(app).listen(process.env.PORT || 3000), bu then I got warn: error raised: Error: listen EACCES and same 404. What am I missing here about the port usage?
You can't create a server on port 80 without special permissions. And on another sidenote, you are trying to create 2 servers (one on port 80 and another one on port 3000).
Here's (a part of) what i'm using for my projects:
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, sio = require('socket.io').listen(server)
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
// configure your socket.io instance here
server.listen(app.get('port'), function() {
// server started
});

Socket.io and Express 3

I created a express 3 app with the express generator and installed socket.io.
On app.js im emiting a message:
io.sockets.on('connection', function(socket) {
socket.emit('init', { msg: 'Welcome'});
});
At server side I wrote:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src='/socket.io/socket.io.js' />
<script>
var socket = io.connect('http://127.0.0.1:3000');
socket.on('init', function (data) {
console.log(data.msg);
});
</script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
If I run app.js It should print "Welcome" on the console, but its not priting anything. I checked if /socket.io/socket.io.js is accesed and it does.
When running the app I get:
info - socket.io started
Express server listening on port 3000
GET / 200 28ms - 472
GET /stylesheets/style.css 200 163ms - 110
debug - served static content /socket.io.js
Am I missing something? I followed the socket.io webpage examples, but it seems that server is running fine... maybe something at the client-side?
EDIT: I also tried var socket = io.connect('http://127.0.0.1', { port: 3000 } ); on the client side, and also running all socket client side from the body.
Doing a console.log on the io.sockets.on event gave nothing... so "connection" is never reached.
app.js:
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
var server = http.createServer(app)
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', routes.index);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = require("socket.io").listen(server)
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
});
index.html:
<script>
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
});
</script>
In your browser's console you should see an object containing "hello": "world".
adding a index.jade file to the example I posted before
server.js
var app = require('express')()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server)
server.listen(3000)
io.set('loglevel',10) // set log level to get all debug messages
io.on('connection',function(socket){
socket.emit('init',{msg:"test"})
})
app.get('/',function(req,res){
res.render('index.jade')
})
/views/index.jade
doctype html
html
head
script(src="/socket.io/socket.io.js")
script.
var sockets = io.connect()
sockets.on('init',function(msg){
alert(msg.msg)
})

Resources