socket.io not emitting - javascript

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>

Related

Simple server-client socket io

I'm trying to set up a simple server/client architecture using socket.io.
I have the following code in my main.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
res.send('<h1>Hello world</h1>');
});
io.on('connection', function(socket){
console.log('a user connected')
})
http.listen(3001, () => {
console.log('listening on *:3001');
});
I have the following code in my client.js
const io = require("socket.io-client");
let socket = io(':3001')
I then run node main.js which prints "listening on *:3001", however when I run node client.js the expected "a user connected" is not printed. What am I missing in this simple architecture?
It should work if you write it like this in your client.js:
let socket = io('http://localhost:3001/')

Socket.io Basic web socket connection with url?

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.

Node.js express does not print anything

So I moved app.listen to the top, but now it gives me an error that port is in use. I believe this is because I set up my websocket on this port, but how do I do it then?
var server = require('websocket').server, http = require('http');
var express = require('express');
var app = express();
app.listen(8080);
var socket = new server({
httpServer: http.createServer().listen(8080)
});
socket.on('request', function(request) {
var connection = request.accept(null, request.origin);
app.get('/', function(request, response) {
var id = request.query.steamid;
console.log("STEAMID:",id);
response.send("I have received the ID: " + id);
});
connection.on('message', function(message) {
connection.sendUTF(message);
});
connection.on('close', function(connection) {
console.log('connection closed');
});
});
I believe you need to listen on connection and not on request
socket.on('connection', function(sock) {
sock.on('message', function(message) {
sock.send(message);
});
sock.on('close', function() {
console.log('connection closed');
});
});
put your app.listen(3000); outside of request event.
so,your express server get chance to initialize port to listen.
Currently it is in callback of request event and it will get called once client-server connection of web-socket is established.
As far as URL concern
ws://localhost:8080/?steamid=123456789
you have configured websocket to listen on port 8080.But your express is configured to listen port 3000.So it is not possible to catch request on express Server configured on different port which is requested through web-socket configured on another different port.
url should be like this.
http://localhost:3000/?steamid=123456789
because your express server using http protocol and not websocket

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 setup causes hundreds of transport polling GET requests

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.

Categories

Resources