My app no longer works after upgrading socketIO from 0.9.17 to 1.3.4.
Can anyone help? this is my app
Normally when I launch I should see
info -socket.io started
Now I see nothing, no errors either.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server,{transports:['flashsocket', 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']});
var port = Number(8080);
server.listen(port);
app.use(express.static(__dirname + '/'));
var temp;
var _this = this;
io.on('connection', function (socket) {
console.log('connection '+socket)
socket.on("data",function(d){console.log('data from flash: ',d);});
socket.emit("message","wtfwtwftwftwf hello from server");
socket.on('disconnect', function (socket) {
console.log("disconnect");
});
console.log('_this ='+_this);
_this.socket=socket;
});
The current socket.io documentation suggests this which is slightly different than what you have:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server, {transports:['flashsocket', 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']});
var port = Number(8080);
server.listen(port);
app.use(express.static(__dirname + '/'));
var temp;
var _this = this;
io.on('connection', function (socket) {
console.log('connection '+socket);
socket.on("data",function(d){console.log('data from flash: ',d);});
socket.emit("message","wtfwtwftwftwf hello from server");
socket.on('disconnect', function (socket) {
console.log("disconnect");
});
console.log('_this ='+_this);
_this.socket=socket;
});
Also, your assignment of _this.socket=socket; looks troublesome because this appears like it would only ever work for one client connected at a time. As soon as you have more than one webSocket connection, the second connection would overwrite the first.
Also, you should make absolutely sure you're using compatible socket.io libraries on client and server (e.g. same version on both ends).
Related
When users do a GET /check/health, this client should talk to Server and sever should give the client the answer..
But the message from the server is not received on the client..
Client side - also acting as a webserver
var io = require('socket.io-client');
var socket = io.connect('http://localhost:4000', {reconnect: true});
var express = require('express');
var app= express();
var path = require('path');
var bodyParser= require('body-parser');
app.use(express.static(__dirname+"/public/"));
app.use(bodyParser.json());
app.set('views',path.join(__dirname,'/public/html'));
app.engine('html', require('ejs').renderFile); //specify which template engine to use
app.set('view engine', 'ejs');
app.get('/check/health',function(req,res){
//console.log('Connected Success!!');
socket.on('connect', function(socket) {
console.log('Connected!');
});
socket.emit('data', 'I need your health status');
socket.on('data', function(data) {
console.log('Message from monitoring is : ' + ': ' + data);
});
socket.on('server data', function(data) {
console.log('Received server data: ' + data);
});
});
app.listen(3000);
console.log("Server running at http://localhost:3000/'");
Server side:
var app = require('express')();
var SERVER = require('http').Server(app);
var io = require('socket.io')(SERVER);
var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
io.on('connection', function(socket){
console.log('connection received from Provisioning ');
// To get messages from Provisioning server
socket.on('data', function(data) {
console.log('Message from provision is : ' + ': ' + data);
});
socket.emit('server data', 'Here is yiour data - 1111');
});
SERVER.listen(4000, function(){
console.log('listening on *:4000');
});
There are a number of potential issues here, but the main one is that your server side code is missing the following very important line:
http.listen(4000);
Adding that should get you started down the right path. Also, I would suggest renaming the http variable to something else, since it's not the http module. server makes more sense to me.
Here's a more minimal example of what you're looking to do. It's missing a few things such as error handling, considering what should happen when a request to /check/health comes in and your socket.io connection isn't up, etc, but I'll leave that as an exercise for you. I also trimmed out some stuff that wasn't relevant to the question (mongoose, ejs templating, etc), so you'll have to add those back in when you're confident that this piece is working as intended.
Client Side
var io = require('socket.io-client');
var socket = io.connect('http://localhost:4000', { reconnect: true });
var express = require('express');
var app= express();
var path = require('path');
// careful here -- the socket.io connection will be made
// outside of the context of the /check/health callback,
// so you should move the connect event handler out here.
socket.on('connect', function(socket) {
console.log('Connected!');
});
app.get('/check/health',function(req,res){
// note the third argument here,
// which can be used as an acknowledgement from the server
// that your client's emit was received
socket.emit('data', 'I need your health status', function ack(data) {
console.log('data emit was acknowledged:', data);
// make sure you send something back to the requester
// or they'll just hang until timeout
return res.json(data);
});
// if you want, you could technically use socket.once('server data'),
// in this location, but this is probably going to be closer
// to the style of communication you actually want --
// which is one response to this specific single socket emit.
});
app.listen(3000);
console.log('Server listening at port 3000');
Server Side
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var express = require('express');
io.on('connection', function(socket){
console.log('connection received from Provisioning');
// To get messages from Provisioning server
socket.on('data', function(data, ack) {
console.log('Message from provision is : ' + ': ' + data);
ack('here is your data - 1111');
});
});
server.listen(4000, function(){
console.log('socket.io server listening on *:4000');
});
I try to create a real time app by socket.io.
Server side:
var express = require('express');
var io = require('socket.io');
var engine = require('ejs-locals');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
app.engine('ejs', engine);
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.redirect('/login')
});
app.use(express.static(__dirname + '/public'));
app.listen(3001);
io.sockets.on('connection', function (socket) {
console.log('Client connected...');
socket.on('send_login_data', function (data) {
console.log(data);
});
});
Client side:
var socket = io.connect('http://localhost:3001');
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
socket.on('connecting', function () {
console.log('connecting...');
});
socket.on('connect', function () {
console.log('connected!');
});
I caught the next error:
GET http://localhost:3001/socket.io/1/?t=1447539302809 404 (Not Found)
As I understand, it's a handshake error.
How can I fix it?
Thanx.
First off, make absolutely sure there are no errors showing anywhere in case some module isn't installed properly.
Then, make sure you have the same version number of socket.io on client and server and that you have the server-side version installed on the server.
Then, I've seen folks have issue with this before, even when following the instructions on the socket.io web site and it's never been clear exactly what was wrong with that sequence. But, what I know is that this sequence will work:
var express = require('express');
var app = express();
var server = app.listen(3001);
var io = require('socket.io').listen(server);
See related issues: Where is my client side socket.io? and Node + Socket.io Connection issue
I don't know if this is causing the issue or not, but you are attempting to redefine the io variable when it has already been declared in this:
var io = require('socket.io');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
The second reference to io = io.listen(server) is essentially this:
var io = require('socket.io');
var app = express();
var server = require('http').createServer(app);
var io = io.listen(server);
Which is not correct Javascript. Again, may not be causing your issue, but it is not technically proper Javascript.
I am not able to run socket.io code in node.js, console.log() is also not displaying when running the code. Below is the code.
app.js
var express = require('express');
var http = require('http');
var app = express();
app.set('port', process.env.PORT || 3000);
app.post('/testStream',test.testStream);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
module.exports.appServer = server;
and I have created a test.js file where I am accessing this exported variable appServer.
var server = require('../app.js');
exports.testStream = function(req,res){
var io = require('socket.io').listen(server.appServer);
io.on('connection',function(socket){
console.log("in socket");
fs.readFile('E:/temp/testimg.png',function(err,buf){
socket.emit('image',{image: true,buffer: buf});
console.log("test image");
});
})
}
when the code runs it stucks and not showing the console.logs(). What I am doing wrong over here. Any help is very much appreciated.
I would suggest following the code structure as suggested in socket.io docs.
Also, you should not be calling io.listen or io.on('connection') inside your testStream express middleware. These are things you should only be doing once, and ideally they should happen during startup, inside app.js and not in reaction to a POST request. In fact, I'm not sure what the purpose of your testStream middleware is, its not even returning any response (eg res.end())
If you want to handle socket connections in a separate module you can, but instead of exporting your app's server the way you are, try passing the io instance as variable to your submodule. In short, try this:
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var test = require('./test')(io);
app.set('port', process.env.PORT || 3000);
server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
test.js
module.exports = function(io) {
io.on('connection', function(socket) {
console.log("in socket");
fs.readFile('E:/temp/testimg.png', function(err, buf) {
socket.emit('image', {
image: true,
buffer: buf
});
console.log("test image");
});
});
};
I am currently learning to use socket.io with node js but I'm having a hard time because I think something may have changed between versions. I have a litte demo using 1.0.4 in which I use something like this to send events from the client and receive them in the server:
SERVER
var socketio = require('socket.io');
var http = require('http');
var app = express();
var server = http.Server(app);
var io = socketio.listen(server);
var port = process.env.PORT || 8080;
server.listen(port, function(){
console.log("Express server listening on port " + port);
});
io.on('connection', function (socket) {
socket.emit('connected');
socket.on('myEvent', function(){
console.log('myEvent has been emitted');
});
});
CLIENT
$(document).ready(function(){
$('#button').click(function(){
emitEvent();
});
});
var socket = io.connect('http://localhost:8080/');
socket.on('connected', function () {
alert('server says I am connected');
});
function emitEvent(){
socket.emit('myEvent');
}
With both versions I can open the socket on the client and receive the 'connected' event sent later from the server than launches the alert function. The problem here is when I want to send any other event from the client. "socket.emit('myEvent');" in the emitEvent function seems to work fine for the 1.0.4 version but not for the 1.0.6 version. I have been looking for info about the changes and trying to understand the whole module but cannot get to the solution. Does anyone know what am I doing wrong? Obviously the way sending client events has changed. I would appreciate if someone could help me with this issue. Thanks in advance.
I didn't understand the problem actually. But here's the code for your functionality.
client:
var socket = io.connect();
$('#button').click(function(){
socket.emit('myEvent');
});
socket.on('connected', function(){
alert "you are connected";
});
server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(app);
var port = process.env.PORT || 8080;
app.listen(port);
io.on('connection', function(socket){
socket.on('myEvent', function(){
socket.emit('connected');
console.log('emmited succesfully');
});
});
In my application i need to connect two socket.io node applications.Using socket.io-client we can do like this.But i don't know how socket.io-client works and where to include that.
First Node Application
var express = require('express')
, http = require('http');
var app = express();
app.use(function (req, res) {
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
io.sockets.on('connection',function(socket){
socket.on('eventFiredInClient',function(data){
socket.emit('secondNodeAppln',data);// i need to get this event in my 2nd node application how can i do this by using socket.io-client
});
});
Second Node Application
var express=require('express');
var http=require('http');
var app=express();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var serverAddress = '127.0.0.1';
var serverPort = 3000; //first node appln port
var clientio = require('socket.io-client');
var socket = clientio.connect(serverAddress , { port: serverPort });
socket.on('connect', function(){
console.log('connected');
});
socket.on('disconnect', function(){
console.log('disconnected');
});
var io = require('socket.io').listen(server);
server.listen(6509);
//here i need to get the 'secondNodeAppln' event raised in first node application.How can i do this.
You need to create a socket.io client in your first app:
var io = require('socket.io').listen(server); // this is the socket.io server
var clientio = require('socket.io-client'); // this is the socket.io client
var client = clientio.connect(...); // connect to second app
io.sockets.on('connection',function(socket) {
socket.on('eventFiredInClient',function(data) {
client.emit('secondNodeAppln', data); // send it to your second app
});
});
And in your second app, just listen for those events:
io.sockets.on('connection', function (socket) {
socket.on('secondNodeAppln', function(data) {
...
});
});
There's a bit of a race condition because the code above doesn't wait for a connect event on the client socket before passing events to it.
EDIT see this gist for a standalone demo. Save the three files to a directory, start the servers:
node serverserver &
node clientserver
And open http://localhost:3012 in your browser.