I'm trying to use socket.io with express 4 and express-generator, however I'm having an issue that the connection event from socket.io don't fires. I have the following settings for my project:
./bin/www
var load = require('express-load');
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = require('socket.io').listen(server, {});
load('sockets').into(io);
socket/chat.js
module.exports = function (io) {
var sockets = io.sockets;
sockets.on('connection', function (client) {
console.log('A user had connected: ', client);
});
console.log('Sockets Events: ', sockets._events.connection);
};
The function of the event is properly logged to the conseole, but when I try to connect I don't receive the log from the event.
I already tried the solutions on this thread: Using socket.io in Express 4 and express-generator's /bin/www
But none solved my issue, thanks in advance.
Related
I just set up SocketIO in my PHP project. I am completly new to websockets at all so bear with me.
I am defining the socketIO variable globally
let socketIO = io("http://localhost:3000");
When people are logging in to my application, they are connected to it with their ID comming from the database. The login script just gives back true which redirects the user in very simplified terms:
// get component
$.get(url, data, (data) => {
if (data.status) {
// connect with Node JS server
socketIO.emit("connected", data.user_id);
// redirect
load_new_page("/users/" + data.user_id);
}
});
My concern here now is that people could just go and change the data.user_id to anything they want and receive what ever the chosen id would receive.
My server.js:
// initialize express server
var express = require("express");
var app = express();
// create http server from express instance
var http = require("http").createServer(app);
// include socket IO
var socketIO = require("socket.io")(http, {
cors: {
origin: ["http://localhost"],
},
});
// start the HTTP server at port 3000
http.listen(process.env.PORT || 3000, function () {
console.log("Server started running...");
// an array to save all connected users IDs
var users = [];
// called when the io() is called from client
socketIO.on("connection", function (socket) {
// called manually from client to connect the user with server
socket.on("connected", function (id) {
users[id] = socket.id;
});
});
});
How can I prevent something like this?
I am trying to make a simple server with socket.io and express and connect to it through a website.
when i followed a tutorial on socketio with localhost, everything worked fine, but when i put the server on a vserver, and tried to connect to it, i got this error:
Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR
as well as:
GET https://54.53.0.254:47185/socket.io/?EIO=4&transport=polling&t=O09jjrs net::ERR_SSL_PROTOCOL_ERROR
here is my server code:
const express = require('express');
const app = express();
const server = app.listen(47185);
const socket = require('socket.io');
const io = socket(server)
console.log('server running on port 47185');
io.sockets.on('connection', newConnection);
function newConnection(socket) {
console.log('new connection: ' + socket.id);
socket.on('input', inputLog)
function inputLog(data) {
socket.broadcast.emit('input', data);
console.log(data);
}
}
and here is my client code (this is all that relates to socket.io, the rest is just for the website)
var options = {
rejectUnauthorized:false
}
var socket;
socket = io.connect('89.58.0.199:47185', options);
socket.on('input', foreignInput)
function foreignInput(data) {
terminal_animate('\n' + data)
}
i have tried many different fixes and googled everything i can think of, and i'm just not sure what the problem is.
can anyone help me out with this issue? thanks in advance.
In the documentation, according to the Client Initialization part, in node.js you should provide the protocol when connecting to the server.
// the following forms are similar
const socket = io("https://server-domain.com");
const socket = io("wss://server-domain.com");
const socket = io("server-domain.com"); // only in the browser when the page is served over https (will not work in Node.js)
The first two example shows the secure https/wss as protocol, for that you need to serve the required files from the server, example in the documentation.
With http/ws as protocol it should work, but the communication will not be secure.
The Server Initialization / With Express shows an example to call .listen on the return value of createServer from the http module, with the app given as a parameter.
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, { /* options */ });
io.on("connection", (socket) => {
// ...
});
httpServer.listen(3000);
With a caution that says:
Using app.listen(3000) will not work here, as it creates a new HTTP server.
I'm trying to build a simple flutter chat application using a node.js matchmaking server. I've worked with this for a few hours already but I simple cannot get the app to connect with the server.
Here's the node js server:
var express=require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var allClients = {};
io.on('connection', function (socket) {
io.to(socket.id).emit('userCount', Object.keys(allClients).length);
console.log(socket.id,'joined');
//match making logic
});
var port = 8080;
console.log(port);
server.listen(port);
Flutter connecting code:
//Find a match for the user
void findMatch() async {
SocketIO socketIO = SocketIOManager().createSocketIO("http://192.168.0.32:8080", "/");
print('Created');
await socketIO.init(); //code execution pauses indefinitely at this line
print('Initialized');
await socketIO.connect();
print('Connected');
socketIO.sendMessage('new user', data);
socketIO.subscribe('match found', (data) async {
UserData peerData = await getUserData(data.peerId);
redirectToPage(context, Chat(peerId: data.peerId, peerData: peerData));
});
}
When the function is run, the code execution pauses at the line shown above, and the node js server doesn't react at all. However this shows up on the debug console.
D/FlutterSocketIoPlugin: FlutterSocketIoPlugin( 4490): onMethodCall: socketInit - domain: http://192.168.0.32:8080 - with namespace: /
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: added SocketIO( 4490): http://192.168.0.32:8080/
D/FlutterSocketIoPlugin: SocketIO( 4490): connecting...null
Any help is appreciated. Thank you!
I wrote a simple node js client as suggested in the comments, and it connects to the server successfully.
//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');
Edit:
Removing the 'await's before the socket functions in findMatch() gets me this.
D/FlutterSocketIoPlugin: SocketIO(21368): reconnect_error: [{"cause":{"cause":{"detailMessage":"CLEARTEXT communication to 192.168.0.32 not permitted by network security policy","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"websocket error","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"Connection error","stackTrace":[],"suppressedExceptions":[]}]
I tried android:usesCleartextTraffic="true" in AndroidManifest.xml but it doesn't seem to work. Changing http to https gives SSL handshake aborted. Maybe deploying the socket server on a remote machine with an SSL certificate will work? Will continue digging.
Downgrading my server's socket.io version worked for me. Just as above, if you are using nodejs try uninstalling socket.io and installing an older version as follows:
npm uninstall socket.io
npm install socket.io#2.3.0
Most flutter socket io client packages are compatible with socket.io version 2.3.0. I would recommend you downgrade to this incase you are experiencing a similar problem.
I tried above code with this flutter plugin here as I think you are also using the same, but I also got the same problem. I tried to see any error log generated by Logcat and I found an entry connecting...null and it was stuck there but don't know how to fix or what is the problem. I tried it with another flutter plugin here and tested it in emulator, it worked fine for below sample code. If you can use a different flutter plugin then this might be useful.
var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log(socket.id, 'joined');
socket.on('/test', function (msg) {
console.log(msg);
});
});
var port = 8080;
console.log(port);
server.listen(port);
Flutter client code -
IO.Socket socket = IO.io('http://10.0.2.2:8080', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
socket.connect();
socket.emit('/test', 'test');
Try downgrading your server's socket io version. Some socket io client packages(flutter) are not compatible with the latest server-side socket io (node.js). My server configuration was using version 3.0.4. For some reason, it was incompatible with adhara_socket_io: 0.4.2 and socket_io_client: 0.9.12. By downgrading my node.js socket io version worked for both client libraries
npm uninstall socket.io
npm install socket.io#2.3.0
work too
server(nodejs) => "socket.io": "^2.4.1"
client(flutter) => socket_io_client: ^1.0.1
I am attempting to get some real time notifications into my Laravel 5 app. Building locally on a vagrant box with Homestead.
I can not work out what the issue is with the following set up.
My server.js is as follows ...
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(3000);
io.on('connection', function (socket) {
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
Then my client code is to subscribe:
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3000');
socket.on('message', function (data) {
alert(data);
});
</script>
Firebug keeps returning:
GET http://127.0.0.1/socket.io/?EIO=3&transport=polling&t=1430825965165-1
Aborted
Chrome tools shows me the following:
http://127.0.0.1:3000/socket.io/?EIO=3&transport=polling&t=1430826106108-3 net::ERR_CONNECTION_REFUSED
Pretty new to NodeJs and very confused. Spent a good 4 hours now trying to work it out.
Any pointers?
many thanks, Dean.
First make sure that you have installed all dependencies of your server.js file, if you are working with Homestead, execute the following command in your root project directory:
npm install express redis socket.io --save
Wait until installation finish and start the server with:
node server.js
Use your project's virtual host name for connect with socket.
It works for me.
Edit this in your client code.
var socket = io.connect('http://' + location.host + ':3000');
I have fetched a copy of the latest Mean.io and noted quite a number of changes compared to the previous version I have been working with before. Now, what I am doing is creating a very basic chat application that uses socket.io with rooms. Following the basic setup in the Socket documentation I have to implement the following:
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Where would I define the basic socket room setup?
socket.set("log level", 1);
var people = {};
var rooms = {};
var clients = [];
You can set the socket.io to listen on your server on
/server/config/system/bootstrap.js
Require the socket.io module
var express = require('express'),
appPath = process.cwd(),
io = require('socket.io');
Now set the socket.io to listen on your app
// Express settings
var app = express();
require(appPath + '/server/config/express')(app, passport, db);
io = io(app.listen(3000));
return io;
Then you need to inject the socket.io object into your app on bootstrapDependencies() function.
function bootstrapDependencies() {
...
// Register socket.io dependency
mean.register('io', function() {
return io;
});
}
Mean.uses this project for its dependency injection
https://www.npmjs.org/package/dependable
Finally you need to configure your app to listen on every socket connections
probably you want to do these on your main app's router at
/server/routes/index.js
Sample connection handler
var io = require('meanio').io;
io.on('connection', function (socket) {
// emit data to the clients
socket.emit('news', { hello: 'world' });
// event listeners
socket.on('my other event', function (data) {
// call your controller function here
Controller.action(data);
});
});
And more importantly, don't forget to setup socket.io on the client side.
// on '/server/views/includes/foot.html'
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
</script>
I've just responded to another SO post (Mean.io framwork with socket.io).
Note: I'm using mean.io v0.5.26 and socket.io v1.1.0.
Pasting my answer again, here.
I also faced the same issue and took me about a week to finally get it right. I'll try to explain what I did:
app.js
In this file, I just invoke the code that creates and sets up a socket.io object for me, which is then passed to the routes module.
'use strict';
/*
* Defining the Package
*/
var Module = require('meanio').Module;
var MeanSocket = new Module('chat');
/*
* All MEAN packages require registration
* Dependency injection is used to define required modules
*/
MeanSocket.register(function(app, http) {
var io = require('./server/config/socketio')(http);
//We enable routing. By default the Package Object is passed to the routes
MeanSocket.routes(io);
return MeanSocket;
});
server/config/socketio.js
This file simply configures the socket.io object. Please note that I had to upgrade meanio module to version 0.5.26 for this work, as http object (express server) is not available in older meanio versions. Moreover, in case you want to use ssl, you can inject https instead of http.
'use strict';
var config = require('meanio').loadConfig(),
cookie = require('cookie'),
cookieParser = require('cookie-parser'),
socketio = require('socket.io');
module.exports = function(http) {
var io = socketio.listen(http);
io.use(function(socket, next) {
var data = socket.request;
if (!data.headers.cookie) {
return next(new Error('No cookie transmitted.'));
}
var parsedCookie = cookie.parse(data.headers.cookie);
var sessionID = parsedCookie[config.sessionName];
var parsedSessionID = cookieParser.signedCookie(parsedCookie[config.sessionName], config.sessionSecret);
if (sessionID === parsedSessionID) {
return next(new Error('Cookie is invalid.'));
}
next();
});
return io;
};
routes/chat.js
Finally, use the routes file to define the socket events, etc.
'use strict';
// The Package is passed automatically as first parameter
module.exports = function(MeanSocket, io) {
io.on('connection', function(socket) {
console.log('Client Connected');
socket.on('authenticate', function(data, callback) {
});
});
};
Hope this helps!
The latest update v0.4.0 requires another strategy to get socket.io setup. I'm currently in discussion with one of the project contributors to validate my solution. I'll make sure to update my response once I'm 100% sure.
The meanio package is now where the bootstrap functionality is located, as well, where express setup is being called from.
Looks like the mean.io guys have recently released an official Socket.io implementation that integrates directly with their stack. Check it out on Github.