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');
});
});
Related
I am trying to emit message from client side with socket.io ...
Here is my client code:
var socket = io.connect('http://localhost/');
socket.on('connect', function(data){
setStatus('connected');
socket.emit('subscribe', {channel:'update.comment'});
});
Server:
io.sockets.on('connection', function (socket) {
socket.emit('message', { text : 'Welcome!' });
socket.on('subscribe', function (data) {
socket.join(data.channel);
redisClient.subscribe(data.channel);
});
});
Also I get this error message in console:
GET
http://localhost/socket.io?EIO=3&transport=polling&t=1442169984269-1
404 (Not Found)
Full serever:
var app = require('express')();
var http = require('http').Server(app);
var redis = require('ioredis');
var io = require('socket.io')(http);
redisClient = redis.createClient();
//look for connection errors and log
redisClient.on("error", function (err) {
console.log("error event - " + redisClient.host + ":" + redisClient.port + " - " + err);
});
io.sockets.on('connection', function (socket) {
socket.emit('message', { text : 'Welcome!' });
//on subscription request joins specified room
//later messages are broadcasted on the rooms
socket.on('subscribe', function (data) {
socket.join(data.channel);
redisClient.subscribe(data.channel);
});
});
redisClient.on('ready', function(data) {
console.log('#redis ready');
});
redisClient.on("message", function(channel, message){
console.log(channel);
var resp = {'text': message, 'channel':channel};
io.sockets.in(channel).emit('message', resp);
});
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
New Problem Recognized:
Your server is listening on port 3000, but you are attempting to connect on port 80. The error message http://localhost/socket.io?EIO=3&transport=polling&t=1442169984269-1 has no port number on it so that defaults to port 80.
That error message means that your server-side socket.io code is not initialized correctly and thus is not listening for the HTTP request that starts all webSocket connections so when the browser tries to connect on that URL to initiate a socket.io connection, there's nobody on the server-side listening so the web server returns a 404 error back to the browser.
If you are using Express, this is the minimal socket.io initialization to hook it into your server:
var express = require('express');
var app = express();
var server = app.listen(8081);
var io = require('socket.io').listen(server);
For a plain HTTP server, this is the minimal socket.io initialization:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
app.listen(80);
As always, if you show us the socket.io and web server initialization code you are using, we can help you better with your specific code issue.
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");
});
});
};
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).
My app work locally but when i deploy to heroku the requests to myapp.herokuapp.com/socket.io get a 404 response.
Here's my code :
var express = require('express');
var http = require('http');
var app = express();
var port = 8080;
// Configuration of the server
require('./ServerConfig').serverConfig(app, express);
var server = http.createServer(app).listen(port)
var io = require('socket.io').listen(server);
io.on('connection', function(socket){
console.log('a user connected');
socket.on('message', function(msg){
console.log(msg);
io.emit('message', msg);
});
});
I have just started using nodejs and i dont really understand why it crashes.
Could someone either explain the cause of this bug or how to debug this ?
Thanks !
Replace line 4 with:
var port = process.env.PORT || 8080;
On Heroku you should bind to the PORT environment variable. See:
https://devcenter.heroku.com/articles/runtime-principles#web-servers
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.