I want to create a websocket to add a communication between my angular app and my database. The app shall be able to save a question in a database & to notify the user when somebody answered.
Unfortunately I tried some tutorials which all don't work. I'm totally new to this because I use apache usually. So If you know a "working", very basic (beginner) tutorial, which doesn't require to install lots of additional things like yeoman etc. I would be glad.
In the current tutorial I get the error message:
You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.
My server.js:
var connect = require('connect'),
serveStatic = require('serve-static'),
socket = require('socket.io');
var server = connect();
server.use(serveStatic(__dirname+'/../client'));
server.listen(8080);
var io = socket.listen(server);
console.log("Server started and listen to http://127.0.0.1:8080");
without
var io = socket.listen(server);
it serves my static page.
This error is on my other approach:
has no method 'use'
My server.js
var connect = require('connect');
var http = require('http');
var serveStatic = require('serve-static');
var app = connect();
var server = http.createServer(app).use(serveStatic(__dirname+'/../client')).listen(3000);
var socket = require('socket.io');
var io = socket.listen(server);
As always if you struggle long the solution comes quick after posting. That one works for the beginning:
var connect = require('connect');
var http = require('http');
var app = connect();
var fs = require('fs');
var index = fs.readFileSync(__dirname+'/../client/index.html');
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end(index);
}).listen(3000);
var socket = require('socket.io');
var io = socket.listen(server);
Related
I'm trying to see a console.log message without results from the socket when someone connects to application. Here is what i have on /app.js and /bin/www files:
Just a way to return a message on console for check if the socket works on
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var session = require('express-session');
var socket = require('socket.io');
var app = express();
// socket.io
var io = socket();
app.io = io;
// var for routes
var index = require('./routes/index');
var users = require('./routes/users');
var projects = require('./routes/projects');
var messages = require('./routes/messages');
//socket message
io.on( "connection", function(socket){
console.log( "A user connected" );
});
www
var app = require('../app');
var debug = require('debug')('archiers:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
// socket.io
var io = app.io;
io.attach(server);
It would seem that you are working with some example code (rather than having written all of that yourself).
The example code you are using is quite a bit longer than it needs to be to accomplish your goals this early on.
For one thing your app.js is not "listening" on any port number - so it cannot possibly get a connection to work.
I can see your www js file would have to cause an error with process.env because the browser has no such variable.
Since you are not getting an error in your browser Console that means there must be a problem with the HTML file (which you have not posted thus far.
I expect there are other problems with the example code you are using that I have not seen.
Since you do not yet understand enough details of the code, I would suggest you start over.
You need to start with a smaller project.
Search the internet for a very small io.js example that works when you download and run it and go from there.
It will be much easier that way.
I am a ios developer, the Objc-Socket.io library is still support socket.io 0.9.x
I use Express 4.0 with my nodejs server:
server.js
var express = require('express')();
var io = require('socket.io');
io.listen(express);
But I run it in terminal, it throw me an error:
% node test
Socket.IO's `listen()` method expects an `http.Server` instance
as its first parameter. Are you migrating from Express 2.x to 3.x?
If so, check out the "Socket.IO compatibility" section at:
https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
This code should do the trick:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app).listen(1337);
var io = require('socket.io').listen(server);
io.on('connection', function(socket) {
//emit and listen messages
});
app.get('/', function(req, res) {
//do something
});
I need to access my socket.io instance in some differents files, how do you make it works?
Here is what i tried:
main.js
var app = express();
var sockets = require('./sockets');
sockets.listen(app)
sockets.js
var io = require('socket.io');
exports.listen = function(app) {
io = io.listen(app);
//...
}
exports.io = io;
SomeClass.js
var io = require('./sockets').io;
var SomeClass = function() {
var Clients = io.sockets.clients('room');
//io is undefined...
}
exports.SomeClass = SomeClass;
In your file, io.sockets is undefined because you are starting your server incorrectly. Socket.IO expects a HTTP server instance, and you are instead passing an Express instance. You are also trying to change a variable after it has been exported, and that does not work. This is what you should be doing:
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server):
server.listen(80);
If you still wanted to split this up into files, you would have to put your Socket.IO instance in your main application, and pass it to other modules when requiring them.
I recently updated socket.io to latest version which is 0.9.8
Last time I worked with the app, I did something like this:
io.sockets.emit("logged",this);
And it worked. Now I get:
TypeError: Cannot call method 'emit' of undefined
at new Agent (/var/www/panel/models/agent.js:29:16)
at module.exports (/var/www/panel/modules/app.js:35:47)
at Query.Client.query (/var/www/panel/node_modules/mysql/lib/client.js:108:11)
at Query.EventEmitter.emit (events.js:85:17)
at Query._handlePacket (/var/www/panel/node_modules/mysql/lib/query.js:51:14)
at Client._handlePacket (/var/www/panel/node_modules/mysql/lib/client.js:319:14)
at Parser.EventEmitter.emit (events.js:88:17)
at Parser.write.emitPacket (/var/www/panel/node_modules/mysql/lib/parser.js:71:14)
at Parser.write (/var/www/panel/node_modules/mysql/lib/parser.js:576:7)
at Socket.EventEmitter.emit (events.js:88:17)
I thought it was because something about scope or whatever so I just did this:
// server.js
var express = require('express'),
server = express(),
Routes = require('./routes'),
App = require('./modules/app.js'),
database = require('./libraries/mysql.js'),
io = require('socket.io'),
mysql = require('mysql');
server.listen(8080);
io.listen(server);
io.sockets.emit('Hi there', {});
And it just doesn't work, same error, different line.
What am I doing wrong?
You need to save the return value of socketio.listen and interact with that. I recommend you follow the examples at socket.io. Something like this should do the trick:
var express = require('express'),
server = express(),
socketio = require('socket.io');
server.listen(8080);
var io = socketio.listen(server);
io.sockets.emit('Hi there', {});
Or even:
var express = require('express'),
server = express(),
io = require('socket.io').listen(server);
server.listen(8080);
io.sockets.emit('Hi there', {});
I'm trying to get connect and socket.io to work together nicely and simply. I have the following code on server side:
var connect = require('connect'),
io = require('socket.io');
var app = connect().use(connect.logger('dev'));
var sio = io.listen(app);
app.listen(8000);
when i open http://localhost:8000/socket.io/socket.io.js i'm get error:
Cannot GET /socket.io/socket.io.js
And Socket.IO not work, i'm trying copy file and load from another location, but socket.io requests do not reach the server
SOLUTION
if anyone comes to this issue, you need to wrap the connect/express app in a node http.Server. The app.listen() method is a convenience method for this and returns the server:
var io = require('socket.io');
var app = connect();
var server = app.listen(3000);
io.listen(server);
or the following is equivalent:
var io = require('socket.io');
var http = require('http');
var app = connect();
var server = http.createServer(app);
server.listen(3000);
io.listen(server);