I am using swaggerexpress middleware and swagger.
I can't get to work with socket.io
What is the proper way to attach socket.io to my server created?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
var io = require('./api/helpers/socketio');
module.exports = app;
var config = {
appRoot: __dirname
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
swaggerExpress.register(app);
app.listen(10010, function () {
console.log('Application is start listening on localhost:10010');
});
io.on('connection',function(socket){
console.log("A user is connected: " + socket.id);
io.emit('message', "Welcome")
});
});
io.attach(app);
With that approach, my server is not getting up, got an error on socket.io attaching to app.
If you're okay using a different port for socket.io, you could do something like this:
var io = require('socket.io')(10011);
// Or maybe in your case:
// var io = require('./api/helpers/socketio')(10011);
io.on('connection', function(socket) {
console.log('user connected');
});
On the client you'd connect to it like this:
var socket = io('http://localhost:10011');
socket.on('connect', function() {
console.log('Socket connection established');
});
Related
I am making a real-time Lumen API. For that i have used Node.js to create the server.
It works perfectly fine on localhost, but not when published
This is the code for my Node Server.js
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var Redis = require('ioredis');
var redis = new Redis();
app.listen(6001, function() {
console.log('Server chalu hua');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
console.log('Lijiye Nya connection bna diya gya');
});
io.on('disconnect', function(socket) {
console.log('Connection Dropped');
});
redis.psubscribe('*', function(err, count) {
//
});
redis.on('pmessage', function(subscribed, channel, message) {
console.log(channel);
message = JSON.parse(message);
console.log(message);
io.emit(channel, message.data);
})
Can someone tell what to do, to make it work in Production
When no room is specified client receive the message but when specify a room I am unable to receive message on client.
server.js
var socket = require('socket.io');
var mysql = require('mysql');
const path = require('path');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = PORT;
io.on('connection', (socket) => {
console.log('new connection made');
socket.on('subscribe', function (room) {
socket.room = room;
socket.join(socket.room, function () {
console.log('joined:' + room); // outputs joined: 1
socket.on('send-message', (data) => {
io.to(data.room).emit('message-received', data.message);
console.log("sent to room:" + data.room); // outputs sent to room: 1
});
});
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
client.js
this.socket = io.connect('ws://IP:PORT');
this.socket.on('connect', () => {
console.log("connection made"); // it output connection made in console
this.socket.emit('subscribe', 1);
});
this.socket.on('message-received', (message: any) => {
console.log(message);
});
on server.js I have tried several options below but still unable to emit 'message-received' on client side:
// io.emit('message-received', data);
// io.to(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
// io.sockets.in(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
//io.broadcast.to(data.room).emit('message-received', data.message);
using latest socket.io library with angular 4
based on what i see on your clientside and serverSide code, I believe the problem is in the clientSide code...
On your server, inside the 'subscribe' event the server is also listening for 'send-message' event, which you're never emiting from the client side!!
Therefore, if you emit 'send-message' event with data(this should include message) as parameter, only then the server would emit 'message-received' event to the client..
HOPE THIS HELPS!
Lets say I have the following NodeJS file:
var https = require("https");
var express = require("express");
var app = express();
var options = {};
var serverPort = 8443;
var server = https.createServer(options, app);
var io = require('socket.io')(server);
var numUsers = 0;
app.get('/', function(req, res){
res.sendFile('/home/domain/index.php');
});
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
});
server.listen(serverPort, function(){
console.log("\n--------------------------------");
console.log('Node HTTPs Server');
console.log('Currently Listening on port %d',serverPort);
console.log("--------------------------------");
});
Since I can't get SNI to work on my server, I'll have to go the old fashioned way and write a script for each subdomain. But what I'd like to do is have the functions inside of the io.on('connection', function(socket) {} area to be included. So not included like a class or anything like that, but literally the code is just taken from another file and processed as if it were in that file already. A lot like PHP does includes. Is this possible?
Simplest solution would be to read code using fs.readFile[Sync] and pass it to eval inside io.on('connection', function(socket) {})
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
// eval function loaded outside io.on('connection')
eval(someFunctionBody);
// or
eval(fs.readFileSync('path/to/function/body.js'));
});
Can't you just use require?
functions.js
function myFunc() {
console.log("I am a funky func");
}
module.exports = {
myFunc,
myOtherFunc,
};
index.js
var https = require("https");
var express = require("express");
// snip
var funcs = require('./functions');
io.on('connection', function(socket){
// snip
funcs.myFunc();
});
I use node.js as server and my ip is example.com:4000. So my endpoint of socket on server side should be example.com:4000. I manage to get it work even when I try to emit something from localhost to example.com:4000.
But when I have an app (I'm using ionic with a real device) but the socket seems didn't send it out the emit of socket.io. I wonder why, it has been 2 days I try to debug this issue.
my code on server side
var server = require("http").Server(express);
var io = require("socket.io")(server);
server.listen(400);
io.on('connection', function(client) {
client.on('msg', function(data) {
console.log(data)
});
});
client side
//angular service
.factory('socket',function(socketFactory){
var myIoSocket = io.connect('http://example.com:4000');
mySocket = socketFactory({
ioSocket: myIoSocket
});
return mySocket;
});
//within my controller
socket.emit('msg',data);
To summarize, things worked on localhost but not when I try on an app?
Try to run this code, since I know that example is working:
Factory
MyApp.factory('socket', function ($rootScope) {
var socket = io.connect('http://localhost:9000');
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
Controller
MyApp.controller('MainCtrl', function($scope, socket){
$scope.users = [];
socket.emit('connection'); });
...
Server side
"use strict";
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log('connected!');
socket.on('disconnect', function() {
console.log('user disconnected');
});
});
server.listen(9000, function() {
console.log('server up and running at 9000 port');
});
I've been trying to figure out why I can't get any emits to show up in my terminal and it seems that everything is running fine.... except for seeing the emits. Here is my code
var express = require('express');
var path = require('path');
// Create a new Express application
var app = express();
var views = path.join(process.cwd(), 'views');
app.use("/static", express.static("public"));
// Create an http server with Node's HTTP module.
// Pass it the Express application, and listen on port 3000.
var server = require('http').createServer(app).listen(3000, function() {
console.log('listening on port ' + 3000)
});
// Instantiate Socket.IO hand have it listen on the Express/HTTP server
var io = require('socket.io')(server);
var game = require('./game');
app.get('/', function(req,res) {
res.sendFile(path.join(views, 'index.html'));
});
io.on('connect', function(socket) {
io.emit('connection', { message: "You are connected!" });
game.initGame(io, socket);
socket.emit('connected', { message: "You are connected!" });
io.sockets.emit('test', 'test')
});
Any help would be great!
Emits are not automatically printed. socket.emit will send a message back to the client, not to the terminal. Use console.log("whatever") to print to the terminal:
io.on('connect', function(socket) {
console.log('Client connected');
socket.on('test', function(data) {
console.log("Got message of type 'test'containing data:", data);
});
});