I am currently trying to make a real time chat room using node, express, and socket.io. When I run the code, I get this error message:
http://gyazo.com/d9956a80a691d1642b438173b0bd85bf
Also, here is my index.js code:
var express = require("express");
var app = express();
var port = 3700;
app.use(express.static(__dirname + "/public"));
app.set("views", __dirname + "/tpl");
app.set("view engine", "jade");
app.engine("jade", require("jade").__express);
app.get("/", function (req, res){
res.render("page");
});
io.sockets.on("connection", function (socket){
socket.emit("message", { message: "welcome to the chat" });
socket.on("send", function (data){
io.sockets.emit("message", data);
});
});
var io = require("socket.io").listen(app.listen(port));
console.log("Listening On Port " + port);
I have searched up over google and found no solutions that were related to my code. Please Help!
You are using the io variable before it's initialized move the var io before the io.sockets
var io = require("socket.io").listen(app.listen(port));
io.sockets.on("connection", function (socket){
socket.emit("message", { message: "welcome to the chat" });
socket.on("send", function (data){
io.sockets.emit("message", data);
});
});
You're using a variable before it's declared and your listen() calls look kind of strange.
Instead of doing this:
io.sockets.on("connection", function (socket){
socket.emit("message", { message: "welcome to the chat" });
socket.on("send", function (data){
io.sockets.emit("message", data);
});
});
var io = require("socket.io").listen(app.listen(port));
You should do something more like this:
var io = require("socket.io")(app);
io.sockets.on("connection", function (socket){
socket.emit("message", { message: "welcome to the chat" });
socket.on("send", function (data){
io.sockets.emit("message", data);
});
});
app.listen(port);
You are accessing the io variable before it is initialized.
Simply move the following line (io variable initialization):
var io = require("socket.io").listen(app.listen(port));
Before the first use of io variable at this line:
io.sockets.on("connection", function (socket){
Related
Lets say I have the following NodeJS file:
var https = require("https");
var express = require("express");
var app = express();
var options = {};
var serverPort = 8443;
var server = https.createServer(options, app);
var io = require('socket.io')(server);
var numUsers = 0;
app.get('/', function(req, res){
res.sendFile('/home/domain/index.php');
});
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
});
server.listen(serverPort, function(){
console.log("\n--------------------------------");
console.log('Node HTTPs Server');
console.log('Currently Listening on port %d',serverPort);
console.log("--------------------------------");
});
Since I can't get SNI to work on my server, I'll have to go the old fashioned way and write a script for each subdomain. But what I'd like to do is have the functions inside of the io.on('connection', function(socket) {} area to be included. So not included like a class or anything like that, but literally the code is just taken from another file and processed as if it were in that file already. A lot like PHP does includes. Is this possible?
Simplest solution would be to read code using fs.readFile[Sync] and pass it to eval inside io.on('connection', function(socket) {})
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
// eval function loaded outside io.on('connection')
eval(someFunctionBody);
// or
eval(fs.readFileSync('path/to/function/body.js'));
});
Can't you just use require?
functions.js
function myFunc() {
console.log("I am a funky func");
}
module.exports = {
myFunc,
myOtherFunc,
};
index.js
var https = require("https");
var express = require("express");
// snip
var funcs = require('./functions');
io.on('connection', function(socket){
// snip
funcs.myFunc();
});
created index.js (server)
var express = require('express');
var app = express();
///creating server
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, { origins:'http://nodejs-atnodejs.rhcloud.com:8000' });
below is remaining code
Routing to index.html page
app.get('/', function (req, res) {
console.log('in socket---' + res);
res.sendfile('index.html');
});
///socket connection
io.sockets.on('connection', function (socket) {
socket.on('chatmessage', function (msg) {
io.emit('chatmessage', msg);
console.log('in socket---' + data);
});
});
/// Listen to Openshift port
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
created index.html(client)
src="http://nodejs-atnodejs.rhcloud.com:8000/socket.io/socket.io.js
var socket = io.connect('http://nodejs-atnodejs.rhcloud.com:8000');
console.log('this is index page');
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
socket.emit('chatmessage', { my: 'data' });
});
When accessed from browser:
Problem is not getting "console.log('chatmessage---' + data);" which is inside the socket..
and keep on getting xhr-polling../t=xxxxx responses..
is my socket working properly?
Both your browser and server code is listening for an event of 'chatmessage' after connection either your browser or server should be emitting the event first and than the other should be listening such as...
// server
io.sockets.on('connection', function (socket) {
socket.emit('chatmessage', /*some data*/);
});
//client
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
});
I'm trying to connect to a socket.But I did not get the socketid on the console.Is it the right way of connecting to a socket ?Can anyone please suggest me ...
My code :
var app = express();
var dir = process.cwd();
app.use(express.static(dir)); //app public directory
app.use(express.static(__dirname)); //module directory
var server =require('http').createServer(app);
var io = require('socket.io')(server);
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
client code :
var socket = io('http://localhost:8085/socket_issue');
socket.on('connect', function(){ console.log('connected to socket'); });
socket.on('error', function(e){ console.log('error' + e); });
socket.on( 'news', function( data ){
console.log(data);
});
socket.on('disconnect', function(){});
You seem to not have a server.listen() in your backend code.
I've edited the server code and it functions correctly:
var app = require('express')();
var dir = process.cwd();
var server =require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
Don't forget to change the port on the front-end and it'll work as expected:
Socket connected :Y7zi7dLRxqBA5nakAAAA
I wrote a very simple demo about socket.io And I package it by using phonegap. I found there is problem. After I open my app about ten seconds ,the connection will disconnect because of xhr poll error.if I refresh the page in disconnect event the error won't come again.
I use 1.2.0 version.here is my code. I already simplify it.
server:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
io.sockets.on('connection', function (socket) {
console.log("disconnect--"+socket.id+"--"+io.sockets.server.eio.clientsCount);
socket.on('disconnect', function () {
console.log("disconnect--"+io.sockets.server.eio.clientsCount);
});
});
http.listen(80, function () {
console.log("server statrt");
});
client:
$(document).ready(function () {
var socket = io("http://192.168.0.106:80");
socket.on('connect', function () {
alert("connect");
});
socket.on('error', function (data) {
alert(data);
});
socket.on('disconnect', function () {
alert("disconnect");
});
socket.on("reconnect", function () {
alert("reconnect");
})
});
thanks for help.my English is not very good
You have to open the socket.io connection when the deviceready event is fired.
document.addEventListener('deviceready', function() {
var socket = io("http://192.168.0.106:80");
socket.on('connect', function() {
alert("connect");
});
socket.on('error', function (data) {
alert(data);
});
socket.on('disconnect', function () {
alert("disconnect");
});
socket.on("reconnect", function () {
alert("reconnect");
});
});
Socket.io example
For those of you using Google Chrome, FYI Chrome does not fire 'deviceready'. Instead you should use 'DOMContentLoaded'.
I have made a simple realtime visitor counter.
You can download it from this repository.
What happens is that disconnect event (even after browser closing) on server is never fired.
server.js is:
(function () {
var app, count, express, io;
express = require('express');
io = require('socket.io');
app = module.exports = express.createServer();
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('stylus').middleware({
src: __dirname + '/public'
}));
app.use(app.router);
return app.use(express.static(__dirname + '/public'));
});
app.configure('development', function () {
return app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function () {
return app.use(express.errorHandler());
});
io = require('socket.io').listen(app);
count = 0;
io.sockets.on('connection', function (socket) {
count++;
io.sockets.emit('count', {
number: count
});
});
io.sockets.on('disconnect', function () {
console.log('DISCONNESSO!!! ');
count--;
io.sockets.emit('count', {
number: count
});
});
app.get('/', function (req, res) {
return res.render('index', {
title: 'node.js express socket.io counter'
});
});
if (!module.parent) {
app.listen(10927);
console.log("Express server listening on port %d", app.address().port);
}
}).call(this);
Script on the client is:
script(type='text/javascript')
var socket = io.connect();
socket.on('count', function (data) {
$('#count').html( data.number );
});
Put your on disconnect code inside your on connect block and edit it a bit like so:
io.sockets.on('connection', function (socket) {
count++;
io.sockets.emit('count', {
number: count
});
socket.on('disconnect', function () {
console.log('DISCONNESSO!!! ');
count--;
io.sockets.emit('count', {
number: count
});
});
});
This way you're detecting when a specific socket (specifically the socket you pass to your anonymous function that is run on connection) is disconnected.
From Socket.IO 1.0 the io.engine.clientsCount property is available. This property tells you how many open connection does your app currently have.
io.sockets.on('connection', function (socket) {
io.sockets.emit('count', {
number: io.engine.clientsCount
});
socket.once('disconnect', function () {
io.sockets.emit('count', {
number: io.engine.clientsCount
});
});
});
Note: Use .once instead of .on and the listener will be removed automatically from the socket what is good for us now, because the disconnect event is only fired once per socket.
Just in case anyone else made this silly mistake: make sure that any socket middleware you've defined calls next() at the end, or else no other socket handlers will run.
// make sure to call next() at the end or...
io.use(function (socket, next) {
console.log(socket.id, "connection middleware");
next(); // don't forget this!
});
// ...none of the following will run:
io.use(function (socket, next) {
console.log(socket.id, "second middleware");
next(); // don't forget this either!
});
io.on("connection", function (socket) {
console.log(socket.id, "connection event");
socket.once("disconnect", function () {
console.log(socket.id, "disconnected");
});
});