missing socket.io.js - node.js

when starting app.js I get
$ node app.js
info: socket.io started
however, running index.html it says that it's missing
GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found) localhost:5
Uncaught ReferenceError: io is not defined
I used npm install socket.io express
app.js
var express = require('express')
, http = require('http');
var io = require('socket.io');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

Your code looks a bit messed up. Got it to work by changing it to this:
var express = require('express')
, http = require('http')
, app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
;
app.configure(function(){
app.use(express.bodyParser());
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
server.listen(process.env.PORT || 3000);

Related

HTML changes not reflecting when running using node and nodemon

I am trying to send my HTML file as a response form my server.js, but it is not adapting to my HTML changed even after restarting the server.
I have also tried nodemon.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.get('/', function(req, res, next) {
res.sendFile(__dirname + '/public/index.html');
});
app.use(express.static('public'));
app.set('view cache', true);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
client.on('messages', function(data){
client.emit('thread', data);
client.broadcast.emit('thread', data);
});
});
server.listen(7777);

Cannot GET /socket.io/?EIO=3&transport=polling&t=LdmmKYz

I have a problem with my node.js server and my ionic 2 with socket.io (websocket) communication.
My ionic app sends this error:
Cannot GET /socket.io/?EIO=3&transport=polling&t=LdmmKYz
and this is my code, I didn't find my mistake.
my node.js code (using express):
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use( (req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:8100"); //The ionic server
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var port = Number(process.env.PORT || 8810);
io.on('connection', function (socket) {
console.log('ping-pong started');
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
and this is the ionic 2 app code (inside the constructor):
this.connect = () => {
this.socket = io('http://localhost:8810');
console.log('socket started');
this.socket.emit('connect', {data: 'data'});
this.socket.on('news', (data)=>{
console.log(data);
this.socket.emit('my other event', { my: 'data' });
});
}
this.connect();
What am I missing?
I found my problem !
my problem was at the server code :
var server = app.listen(8810)
var io = require('socket.io').listen(server);
just this was the problem.
I needed to define where the socket.io listen without it the socket failed .
change it and the error will disappeared.
Try this in the exact order if you are using express 4.
var express = require('express');
var app = express();
var server = app.listen(8810);
var io = require('socket.io').listen(server);
Refer to the API reference here

using socket.io in conjunction with express

I am trying to sent a basic message when users connect and disconnect. Later i want to sent parameters back and forth. But with the following code i do not get the messages print out on the server when they connect/disconnect.
When i replace io.on with server.on i can get the message 'User connected' but not user disconnected when i refresh/close the page. This however is buggy, since not everytime i refresh it logs the message and on first time it sometimes log the message multiple times.
server.js
var //io = require('socket.io'),
http = require('http'),
express = require('express');
var PORT = process.env.PORT || 8080,
HOST = process.env.HOST || 'localhost';
var app = express();
app.use(express.static(__dirname + '/views'));
app.get('/', function (req, res) {
res.sendfile(__dirname + 'index.html');
});
server = http.Server(app);
//io = io.listen(server);
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('User connected');
io.on('disconnect', function(socket) {
console.log('User Disconnected');
});
});
server.listen(PORT, HOST, null, function() {
console.log('Server listening on port %d in %s mode', this.address().port, app.settings.env);
});
New code:
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
var PORT = process.env.PORT || 8080,
HOST = process.env.HOST || 'localhost';
server.listen(PORT);
app.use(express.static(__dirname + '/views')); //need this for my directory structure.
app.get('/', function (req, res) {
res.sendfile(__dirname + 'index.html');
}); //Need this to call my page.
io.on('connection', function( client ){
console.log('Connected');//this does not work.
io.on('disconnect', function( client) {
console.log(client);
});
});
Try reconfiguring your socket, and server instantiation:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(process.env.PORT || 3000);
io.on('connection', function( client ) {
console.log(client) //this will now work
client.on('disconnect', function( id ) {
console.log('user with ID ' + id + ' has disconnected');
});
});
First of all you need to be sure if you have included the client side socket.io files.
<script src="/socket.io/socket.io.js"></script>
Then you need to initialize the socket connection.
<script>
var socket = io();
</script>
The above changes will be in your index.html file.
Now in server.js file,
io.sockets.on('connection', function(socket) {
console.log("User connected");
socket.on('disconnect', function() {
console.log('Got disconnect!');
});
});

Socket.io 'on' is returning undefined

Ok, so I'm trying to learn socket.io and I get this error:
io.socket.on('connection', function (socket)
TypeError: Cannot call method 'on' of undefined
heres my code:
var express = require('express')
, app = express.createServer()
, routes = require('./routes')
, user = require('./routes/user')
, path = require('path')
, io = require('socket.io').listen(app);
// all environments
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.listen(3000);
app.get('/', routes.index);
app.get('/users', user.list);
io.socket.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I know its going to be something rather obvious.
Should be io.sockets.on ("sockets" instead of "socket"):
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I think that this code is no longer working.
Here is something I made to deal with socket.io and a http server.
var app = require('http'),
io = require('socket.io');
var handler = function(req, res) { /* your handler function*/ };
var server = app.createServer(handler).listen( 8000 );
var ios = io.listen(server);
ios.sockets.on('connection', function(socket){
socket.emit('message', {'message': 'hello world'});
});

Socket.io and Express3 - 404 on client request to /socket.io/socket.io.js

I am receiving a 404 when trying to resolve '/socket.io/socket.io.js' from my Node server. I can't determine why.
My server configuration looks like this:
var express = require('express')
, engine = require('ejs-locals')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')
app.use(express.static(__dirname + '/public'));
//define routes
...
app.listen(3000);
//socket io
io.sockets.on('connection', function (socket) {
socket.on('set nickname', function (name) {
socket.set('nickname', name, function () {
socket.emit('ready');
});
});
socket.on('msg', function () {
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
});
});
});
At the client I have this:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I am testing this locally (port: 3000). The Socket code is basically ripped off of the socket.io example to get something working. I have reviewed other posts and can't seem to find where I'm going wrong. Can someone help?
Thanks
Got it!
The HTTP server needs to be listing on the port (3000 in this case.) I then removed the app.listen(3000) as the address will already be in use and is not needed.
Thanks!
var express = require('express')
, engine = require('ejs-locals')
, app = express()
, http = require('http')
, server = http.createServer(app).listen(3000)
, io = require('socket.io').listen(server);

Resources