Socket.io Basic web socket connection with url? - javascript

My client is making a WebSocket request to this URL: ws://localhost:3000/feed/XBTMUR
In my server, I have NodeJs running express. I want to use Socket.io to listen to clients connecting to this URL and send feed data regularly.
I tried this but it is not working:
var app = require('../app');
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);
/**
* Listen on provided port, on all network interfaces.
*/
var io = require('socket.io')(server);
var feed =
io.of('/feed/XBTMUR').on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
io.on('connection', function(socket) {
console.log('a user connected, id ' + socket.id);
socket.on('disconnect', function() {
console.log('a user disconnected, id ' + socket.id);
})
})
setInterval(()=>{
io.sockets.emit('this', { receivers: 'everyone'});
},1000)
server.listen(port);
The client is not using Socket io.

I feel the the implementation is wrong while reading the documentation.
var feed = io.of('/feed') // `/feed` is the namespace
.on('connection', function (socket) {
socket.to('XBTMUR', { hello: 'world' }); // `XBTMUR` is the room / socket id
});
Hope this helps.

Related

socket.io not emitting

So, I have this app called server and the other one called client, server providers all the data for the client to consume. The thing is, when i try to emit from server (port 8080) and receive to client (port 80) nothing happens
server: app.js
var app = require ("./config/server.js");
var http = require('http').createServer(app);
var io = require("socket.io")(http);
http.listen(8080, function(){
console.log('Server side instagram_clone_v01 online');
});
io.sockets.on('connect', function (socket) {
console.log("conectou socket.id="+socket.id);
});
When the server database insert new photo, this is called:
io.emit("newPhoto");
client: app.js
var app = require('./config/server');
app.listen(80, function(){
console.log('Server client instagram_clone_v01 online');
});
var io = require('socket.io');
This is called inside a ejs code:
const socket = io.connect('http://localhost:8080', {transports: ['websocket', 'polling', 'flashsocket']});
socket.on('newPhoto',function(){
load_posts();
});
Edited with the Answer of Federico
I added io.origins('*:*'); to server, but emit isn't emitting
I don't know why you are using io.sockets.on, I couldn't find it in the documentation. I've tried to clean the code, give it a try.
server.js
var app = require ("./config/server.js");
var http = require('http').Server(app);
var io = require("socket.io")(http);
http.listen(8080, function(){
console.log('Server side instagram_clone_v01 online');
});
io.on('connect', socket => {
console.log("user" + socket.request.user.id + "connected");
socket.on('disconnect', function() {
console.log('A user has disconnected');
}
io.emit("newPhoto");
});
client.js
//io() works only when connecting to a socket hosted on the same url/server
// For connecting to an external socket hosted elsewhere, you would use io.connect('URL');
var socket = io();
socket.on('newPhoto',function(){
load_posts();
});
In the page where your user being redirected after login, you should include these scripts:
<script src="/socket.io/socket.io.js"></script>
<script src="/client.js"></script>

Triggering socket.io real-time notifications from Express 4 middleware

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:.

Nodejs implementing socket cluster dont work my sockets

I'm trying to implementing cluster on nodejs and using Socket.io in my application, after some search and introduced about that and finding sticky-socket-cluster i try to use that, here is sample code which i use the documentetion of library, but login socket not working and dont print log
require('sticky-socket-cluster/replace-console')();
var options = {
workers : require('os').cpus().length, // total workers (default: cpu cores count).
first_port : 8000, // 8000, 8001 are worker's ports (default: 8000).
proxy_port : 3000, // default (5000).
session_hash: function (req, res) {
return req.connection.remoteAddress;
},
no_sockets: false // allow socket.io proxy (default: false).
};
require('sticky-socket-cluster')(options, start);
function start(port) {
var express = require('express');
var http = require('http');
var app = express();
var server = http.Server(app);
var socket = require('socket.io')(server);
socket.on('connection', function (socket) {
console.log("socket.io connection handler...");
});
socket.on('login', function (data) {
console.log(data.username);
});
server.listen(port, function () {
console.log('Express and socket.io listening on port ' + port);
});
}

Socket.io not Emitting from Client nor Server?

On client side, I have this code:
var serverAddress = "http://localhost:8081";
var socket = io(serverAddress);
socket.on('connect', function(){
console.log("Connected to server on %s", serverAddress);
});
socket.emit("xxx", {text : "attack"});
And on server, I have this one:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var socket = require('socket.io').listen(server);
socket.on('connect', function() {
console.log('A user is connected to server');
});
socket.on('xxx', function(data) {
console.log(data);
});
connect event is fired and caught on server, but xxx event isn't even fired nor caught. What's wrong? Console.log didn't report any error.
You're confusing the socket.io server with a socket.io connection.
The server receives a connection event when a new client connection is made. The argument for that event (usually called socket) represents that connection. This is the object that you need to use to listen to messages:
// server
...
var io = require('socket.io').listen(server);
...
io.on('connection', function(socket) {
console.log('A user is connected to server');
socket.on('xxx', function(data) {
console.log(data);
});
});

socket.io with express to update variables in the DOM

this is the test case...
app.js
var express = require('express'),
http = require('http'),
//other variables
var app = express();
var server = http.createServer(app);
var io = require("socket.io").listen(server)
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
});
html_index.js
$(document).ready(function()
{
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
});
});
i get this error
WebSocket connection to 'ws://localhost:26000/socket.io/1/websocket/%3Ch2%3Efile%20not%20found!%20error%20404!%3C/h2%3E' failed: WebSocket is closed before the connection is established. socket.io.js:2438
WS.close socket.io.js:2438
Socket.onDisconnect socket.io.js:1967
Transport.onDisconnect socket.io.js:1362
Transport.onClose socket.io.js:1456
(anonymous function)
im using
express 3
socket.io 0.9
nodejs 0.10
the problem was the port
this is the solution
var server = app.listen(26000, function(){ //instead of var server = http.createServer(app);
console.log("Express server listening on port %d in %s mode", app.get('port'),
app.settings.env);
});
//SOCKET.IO
var io = require("socket.io").listen(server)
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
});

Categories

Resources