I'm not getting an error but io.on('connection', function(socket){
console.log('a user connected', socket.client.id);
}); doesn't seem to work when I deployed my application in Linode.
But in the development it's working fine.
server.js ( socket io )
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 8002;
io.on('connection', function (socket) {
console.log('a user connected', socket.client.id); // triggering in the development
});
http.listen(port, function () {
console.log('Express server listening on port ' + port);
console.log('env = ' + app.get('env') +
'\n__dirname = ' + __dirname +
'\nprocess.cwd = ' + process.cwd());
});
client html ( note: i change the localhost to my web app ip)
<script src="http://localhost:8002/socket.io/socket.io.js"></script>
and my application seem to be using the socket.io polling-xhr.js
I'm kind of new to this.
I don't know if this will fix your particular problem, but in order to set up socket.io on the same port that your application uses you can configure it this way:
const express = require('express');
const app = express();
const http = require('http');
const hostname = 'localhost';
const port = 80;
// the express app is registered with the server
const server = http.createServer(app);
// setup socket.io and register it with the server
const io = require('socket.io').listen(server);
// tell the application to listen on the port specified
server.listen(port, hostname, function (err) {
if (err) {
throw err;
}
console.log('server listening on: ', hostname, ':', port);
});
Now socket.io runs on the same port as your application.
Related
I'm having a problem with testing the connection when I use https://localhost:3000/ it connects successfully but I want to use socket Io client on a different device on android application to be precise I searched it up and turns out localhost wont work I have to connect using ipv4 address well I tried it but didnt work - like this http http://192.168.XX.XX:3000 for example so what is the problem why doesnt it connect please help
server code:
var cors = require("cors");
const express = require("express");
const app = express();
const port = process.env.PORT || 3000 ;
const server = app.listen(port, () => {
console.log(`started on ${port}`);
})
const io = require('socket.io')(server, {
cors: { origin: "*" }
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('message', (message) => {
console.log(message);
io.emit('message', `${socket.id.substr(0,2)} said ${message}` );
});
});
require("dotenv").config();
app.use(express.json());
app.use(cors());
//routes setup
const homeGetRoute = require("./routes/test.js");
app.use("/home", homeGetRoute);
app.use(cors());
Hello I am having trouble starting up my server.js. Every time that I would run node towards it. It wills always show this error "listening on *:3000". Here is my code for my server.js.
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/chat', (req, res) => {
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', (socket) => {
console.log('User Online');
socket.on('codeboard-message', (msg) => {
console.log('message: ' + msg);
socket.broadcast.emit('message-from-others', msg);
});
});
var server_port = process.env.YOUR_PORT || process.env.PORT || 3000;
http.listen(server_port, () => {
console.log('listening on *:' + server_port);
});
Do I have to use a different port or am I missing a line of code for this server to work? Any help will be appreciated!
var app = require('express')();
var http = require('http').createServer(app);
var server_port = process.env.PORT || 3000;
http.listen(server_port, () => {
console.log('listening on *:' + server_port);
});
try only this without socket io. If it works, add socket io code
I am building a real-time notification system using socket.io. This is my server-side code at the moment:
bin/www:
var app = require('../app');
var server = http.createServer(app);
var io = app.io
io.attach(server);
server.listen(port, function(err) {
if (err) console.log(err);
console.log('Listening on port ' + port + '...');
});
app.js:
var socket_io = require('socket.io');
var express = require('express');
var app = express();
var io = socket_io();
app.io = io;
require('./config/socket')(app.io);
config/socket.js:
var User = require('../controllers/user');
module.exports = function (io) {
io.on('connection', function (socket) {
console.log('Socket.io connected');
socket.emit('connection', "Connection created.");
socket.on('send notification', function(data) {
User.createNotification(socket.request.user, data);
});
});
};
routes/index.js:
var express = require('express');
var User = require('../controllers/user');
var router = express.Router();
router.post('/order', User.order);
module.exports = router;
controllers/user.js:
var User = require('../models/user').model;
var io = require('socket.io');
module.exports = {
order: function(req, res) {
/* some create order code */
io.emit('send notification', 'Your order was successful!');
res.sendStatus(200);
}
}
I keep getting the error TypeError: io.emit is not a function whenever I try to call the route POST /send even though I am clearly initiating socket.io in my app.js and bin/www files and requiring it in controllers/user.js. All the examples I've seen online emit notifications from within this part:
io.on('connection', function (socket) {
socket.emit(event, msg);
});
but I want my notifications to be triggered from the middleware so I can send custom notifications to the user when certain events happen in the application backend.
Try the following instead:
io.on('connection', function(socket){
socket.on('xxx', function(obj){
io.emit('xxx', {xxx: xxx})
})
})
This should suppress your TypeError:.
I am trying to use socket io so I can dynamically update data on a site:
Edit: Updated Code
In app.js:
var express = require('express');
var app = express();
var routes = require('./routes/index');
app.use('/', routes);
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.emit('news', {hello: 'world'});
socket.on('my other event', function (data) {
console.log(data);
});
});
server.listen(app.get('port'), function(){
console.log('Express listening on port ' + app.get('port'));
});
In index.ejs:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:80');
socket.on('news', function(data) {
socket.emit('my other event', {my: 'data'});
});
</script>
The page loads correctly, however the socketio script does nothing. I have tried to make the code as simple as possible.
Express listening on port 80 outputs to console fine.
in www.
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('untitled: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 = require('http').Server(app);
//var io = require('socket.io')(server);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
Not quite sure by what you mean as "socket script doesn't do anything" as you aren't really doing anything on the client side! From the code posted anyway.
EDIT:
This code works for me on the client and server.
server.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.set('view engine', 'jade');
app.set('views', './views');
app.get('/', function (req, res) {
res.render('index');
});
io.on('connection', function (socket) {
console.log('connected via server');
});
http.listen(3000, function () {
console.log('app listening on port 3000');
});
index.jade (you can use ejs or html)
html
head
script(src="/socket.io/socket.io.js")
script.
var socket = io.connect();
socket.on('connect', function() {
console.log('greetings from client');
});
body
h1 hello world
You can also try serving up the socket.io-client package yourself manually.
Check if app.get('port') works correctly and how do you serve the static site.
I tried to set it explicitly and works:
app.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.set('views', './views');
app.get('/', function (req, res) {
res.render('index');
});
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.emit('news', {hello: 'world'});
socket.on('my other event', function (data) {
console.log(data);
});
});
server.listen(3100, function(){
console.log('Express listening on port ' + 3100);
});
index.ejs
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3100');
socket.on('news', function(data) {
socket.emit('my other event', {my: 'data'});
});
</script>
Or use <script src="http://localhost:3100/socket.io/socket.io.js"></script> if the static site is hosted in elsewhere.
Finally solved it:
Using socket.io in Express 4 and express-generator's /bin/www
I had to make some changes for express 4.0
I'm using express.js server-side and I followed the socket.io setup guide. Unfortunately the socket connection is never successful, and I receive an unruly amount of GET requests that look like this:
Here's my setup:
CLIENT - index.html
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
<script>
// var socket = io.connect('http://localhost');
var socket = io.connect('http://localhost:9000/');
socket.on('connected', function (serverData) {
console.log(serverData);
});
</script>
SERVER - /io/index.js
'use strict';
var socketio = require('socket.io');
var io = null;
module.exports = function(server) {
if (io) return io;
io = socketio(server);
io.on('connection', function(socket) {
console.log('Sockets connected!');
socket.emit('connected', 'Sockets connected!')
})
return io;
};
SERVER - app.js
'use strict';
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
console.error('MongoDB connection error: ' + err);
process.exit(-1);
});
// Populate databases with sample data
if (config.seedDB) { require('./config/seed'); }
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Setup sockets
require('./io')(server);
// Start server
function startServer() {
server.listen(config.port, config.ip, function() {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
}
setImmediate(startServer);
// Expose app
exports = module.exports = {
app: app,
server: server
}
This is tipically what happen, when client does not reach the server.
The client try again and again . . .
For that you have to check your config server-side, checking the port and the path is often the first things you should check.
In your case, maybe you should check this part :
//require('./io')(server); typo error ??
require('./io/index.js')(server);
More further you don't seem to give the good part :
( maybe depending on version you use)
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Setup sockets
require('./io')(server);
I think it should be :
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Setup sockets
//require('./io')(server); |O----------------------------------|
require('./io/index.js')(app);//<---we pass app as argument----|
I hope this will help you.