Laravel 5 - Homestead - Redis - NodeJs - Socket IO not playing nicely - node.js

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');

Related

Flutter socket io doesn't connect to node js socket io 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

Do I need socket.io-client on browser-side of things?

EDIT: The answer appears to be no.
I'm new to Node.js, bower and Socket.IO and I'm not sure what I need for my purpose.
I'm making an app that has a frontend (where browsers connect) and a backend (a single Node.js server).
What do I need to create a Socket.IO server instance on the backend? What do I need on the client-side? Does the Socket.IO package contain both?
First install socket.io using below command
npm install socket.io
and the call socket.io in your server js File
var io = require('socket.io');
And the create connection in your server js file
var app = express();
app.get('/', function(req, res){
fs.readFile('index.html', function(Error,data){
res.writeHead(200,{'Content-Type':'text/html'});
res.write(data);
res.end();
});
});
server = http.createServer(app);
var IO = io.listen(server);
server.listen(3000);
IO.sockets.on('connection', function(socket) {
socket.on('msg_to_server', function(data) {
console.log(data);
});
});
Add this script inside head Tag in your index.html
<script src="/socket.io/socket.io.js"></script>
in your index.html create socketio connection
var socketio = io.connect("127.0.0.1:3000");
send some data to server following way
socketio.emit('msg_to_server',{ message : 'some data' });

var socket = io.connect('http://yourhostname/');?

I try socket.io again since v.1.0 released.
As the doc,
https://github.com/Automattic/socket.io
Server side:
var server = require('http').Server();
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('event', function(data){});
socket.on('disconnect', function(){});
});
server.listen(5000);
Client side
var socket = io.connect('http://yourhostname.com/');
In development, surely
var socket = io.connect('http://localhost:5000/');
It works, but I'm very uncomfortable with hardcoding the hostname(subdomain.domain) in the client code(/index.js).
The index.js is hosted by the http-sever and the socket.io is bundled to the http-server in this configuration.
Is there any smart way not to hardcode the hostname but to code in some relative path?
Thanks.
EDIT:
When I try:
var socket = io.connect('./');
The connection error:
GET http://.:5000/socket.io/?EIO=2&transport=polling&t=1401659441615-0 net::ERR_NAME_NOT_RESOLVED
is like this, so at least the port number (5000) is obtained properly without hardcoding in the client side.
Final answer.
I have totally forgotton that we can obtain the current url/domain in browser.
window.location.hostname
So, simply goes:
'use strict';
/*global window, require, console, __dirname, $,alert*/
var log = function(msg)
{
console.log(msg);
};
log('init');
$('document').ready(function()
{
var io = require('socket.io-client');
var socket = io.connect(window.location.hostname);
socket.on('connect', function()
{
log('socket connected');
});
});
You have to remember that Node.js is not a web server. It's a platform. When you specify a relative path, it doesn't know that you mean "relative to the current domain."
What you need to do is send the domain to the client when you send them the webpage (I don't know the specifics of your setup, but perhaps using a template variable?), and send them the localhost:5000 domain if you're in development, or your real domain if you're in production (alternatively, you can use a library like nconf, but you get the idea).
dunno, so far I did as follows:
'use strict';
/*global window, require, console, __dirname, $,alert*/
var log = function(msg)
{
console.log(msg);
};
log('init');
$.getJSON("../config.json", function(data)
{
var host = data.url;
var port = data.port;
$('document').ready(function()
{
alert(host + ':' + port);
var io = require('socket.io-client');
var socket = io.connect(host);
socket.on('connect', function()
{
log('socket connected');
});
});
});
It's browserified with socket.io-client.

socket.io-client doesn't connect

I am trying to connect two node.js servers using socket.io and socket.io-client. In both cases, I am using v0.9.16.
In my case, I call the servers the STREAM SERVER and the ACTIVITY SERVER where the activity server uses the socket.io-client module.
STREAM SERVER - (THE CODE ON THE SERVER THAT ACTS LIKE A SERVER)
var https = require('https');
var express = require('express');
var socket = require('socket.io');
var securePort = (process.env.LOCAL_HTTPS_PORT || 443);
var sslOptions = //CERTIFICATE
var socketIoConfiguration = //CONFIG VALUES
var app = express();
var server = https.createServer(sslOptions, app);
var io = socket.listen(server, socketIoConfiguration('activityToStream'));
io.sockets.on('connection', function (socket) {
console.log('Activity server connected to stream server.');
});
server.listen(securePort);
ACTIVITY SERVER - (THE CODE ON THE SERVER THAT ACTS LIKE THE CLIENT)
var socketClientModule = require('socket.io-client');
var streamConnectionServer = 'https://165.225.144.273:443';
var activityToStreamSocket = socketClientModule.connect(streamConnectionServer);
activityToStreamSocket.on('connect', function(socket){
console.log('Connected to Stream Server');
});
When I run this code, I don't get any message from either server. However, when I run this code from an HTML page served in Chrome, I see messages on the output of the Stream server:
<!DOCTYPE html>
<html>
<head>
<title>
Test
</title>
<script src="https://165.225.144.273/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('https://165.225.144.273');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
Hello World
</body>
</html>
STREAM SERVER MESSAGES WHEN CLIENT RUN IN CHROME
debug: client authorized
info: handshake authorized UaUDRsA3ZBTgdsiLDCrl
debug: setting request GET /socket.io/1/websocket/UaUDRsA3ZBTgdsiLDCrl
debug: set heartbeat interval for client UaUDRsA3ZBTgdsiLDCrl
debug: client authorized for
debug: websocket writing 1::
So, it makes me think the issue is with my "ACTIVITY SERVER" running socket.io-client, but I cannot figure out why its not working at all (no error messages, etc.)
Use the same version of socket server and client
I had the same issue, but my solution was simple:
My code was wrong here:
var serverSocket = ioclient.connect('127.0.0.1:6000');
Then I wrote 'ws://' before '127.0.0.1', and it began to work.
var serverSocket = ioclient.connect('ws://127.0.0.1:6000');
That gave me a headache for hours.
I was able to get it to work using the following:
1) socket.io v 1.0.0-pre using this command
npm install git+https://github.com/LearnBoost/socket.io.git
2) scoket.io-client v 1.0.0-pre using this command
npm install git+https://github.com/LearnBoost/socket.io-client.git
3) I used an SSL certificate from a CA instead of self signed and then I used a DNS name instead of an IP address (see this on not using unsigned certificates with Socket.io)
Here's my server and client (server acting as client). Reference the Socket.io-client GitHub page.
SERVER CODE
var sslOptions = //CERTIFICATE
var app = require('express')(); // Express 3.x
var server = require('https').Server(sslOptions, app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log('Connection from Activity Server');
for (var i=0; i<100000; i++) {
io.emit('event', i);
}
});
server.listen(443);
CLIENT CODE (SERVER ACTING AS CLIENT)
var now = Date.now();
var socket = require('socket.io-client')('https://example.com:443');
socket.on('connect', function(){
console.log('Connected to Stream Server');
socket.on('event', function(data){
console.log('Ping ' + data);
console.log(now + ' ' + Date.now());
});
});
Using this Socket.io code, I was able to get over 13,000 messages per second. This was done on two Joyent servers in the same data center (Memory 256 MB, CPUs 0.125 and bursting, Network Up to 10 Gbit/s).
When doing more of a "Ping Pong" style messaging, I was able to get about 650 messages per second.
Note the performance numbers are just a datapoint for reference, I didn't do any tweaking, heaving loading, etc.
I got the same situation but I fix this by switching the socketio-client version. I got socketio version 2.3. but I got socketio-client version 3.1. I changed the version of socketio client by using "npm install socket.io-client#2.3". in my client js file I use socket.io-client like that
const io = require('socket.io-client');
const socket = io('ws://localhost:3000',{
});

Use of Socket.io and express 4.3 with express-generator

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.

Resources