Socket.io Error on server - php

I am tried to use socket io on the live server and I got this error.
polling-xhr.js:264 GET http://sub.domain.com:3000/socket.io/?EIO=3&transport=polling&t=MFUVMS5 net::ERR_TIMED_OUT
But on my local server, the files worked perfectly. I am working with socket.io and PHP.
Here are my codes:
server.js
var socket = require('./node_modules/socket.io');
var express = require('./node_modules/express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = process.env.PORT || 3000;
// server active console view
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
// show new added online user
socket.on('now_online', function (data) {
io.sockets.emit('now_online',{
id: data.id,
name: data.name
});
});
});
main.js
var socket = io.connect('http://'+window.location.hostname+':3000');
socket.on('new_online_user', function (data) {
if (login_id != data.online_user) {
$('#contacts-list .contact[data-chat='+data.online_user+']'+' .contact-status').addClass('online');
}
});
package.json
{
"private": true,
"dependencies": {
"gulp": "^3.9.1",
"express": "^4.16.2",
"socket.io": "^2.0.4"
}
}
I was searching in google and StackOverflow about this issue but those solved didn't work for me.
Thanks so much.

Try connecting using only domain without http like:
var socket = io.connect(window.location.hostname+':3000', {transports: ["websocket", "xhr-polling", "htmlfile", "jsonp-polling"]});
It will automatically become ws://sub.domain.com:3000/socket.io/?EIO=3&transport=polling&t=MFUVMS5. I'm using similar to this and working fine.

Related

Node js - Socket is not connecting with https

I am trying to connect to a socket.io-client using the following code: It works HTTP local server. But not working in the HTTPS Live server.
Server:
var express = require('express');
var app = module.exports = express();
var https = require('node:https');
var fs = require('node:fs');
var server = https.createServer({
key: fs.readFileSync("path/key.pem",'utf8'),
cert: fs.readFileSync("path/cert.pem",'utf8'),
requestCert: true,
rejectUnauthorized: false
},app);
var eio = require('engine.io').attach(server);
const io = require('socket.io')(server, {
cors: { origin: "*"}
});
io.on('connection', (socket) => {
console.log('connection');
socket.on('sendChatToServer', (message) => {
socket.broadcast.emit('sendChatToClient', message);
console.log(message);
});
socket.on('disconnect', (socket) => {
console.log('Disconnect');
});
});
server.listen(3000, () => {
console.log('Server is running');
});
Client:
let socket = io("https://mydomain:port");
socket.emit('sendChatToServer', textmessage);

Laravel socket.io doesn't work, failed socket connect, how to fix?

I am trying to create a live chat. Socket.io and node.js
I can't connect the user to my channel.
https://domen.com:8005/socket.io/?EIO=3&transport=polling&t=NYHmcgH :failed
Here is my server.js
var app = require('express')();
var https = require('https').Server(app);
var io = require('socket.io')(https);
var Redis = require('ioredis');
var redis = new Redis();
var users = [];
https.listen(8005, function () {
console.log('Listening to port 8005');
});
io.on('connection', function (socket) {
socket.on("user_connected", function (user_id) {
console.log("user connected " + user_id);
// users[user_id] = socket.id;
// io.emit('updateUserStatus', users);
// console.log("user connected "+ user_id);
});
and here is my blade template
<script>
$(function () {
let user_id = "{{ auth()->user()->id }}";
console.log(user_id);
let ip_address = 'domen.com';
let socket_port = '8005';
let socket = io(ip_address + ':' + socket_port);
});
socket.on('connect', function () {
socket.emit('user_connected', user_id)
});
</script>
express with https needs some keys
var https = require('https')
var app = express()
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
}, app)
.listen(8005, function () {
console.log('Example app listening on port 8005! Go to https://domen.com:3000/')
})
i think you should try first with http, if your code works well then you can upgrade to https
var io = require('socket.io')(http);
http.listen(8005, function () {
console.log('Listening to port 8005');
});
in client side :
let ip_address = 'http://domen.com';

Changing node.js server to Apache server

I was working with react-webpackage and running the project into node.js
Now due to demand , i have to add some php files in the project but i don't know how to add php file in my project and now transfer my project from node.js to Xampp and run my project with xampp... can you please guide me with that.
I am using this webpack "https://github.com/srn/react-webpack-boilerplate".
And my webpack index.js file looks like this.
'use strict';
var fs = require('fs');
var path = require('path');
var express = require('express');
var app = express();
var compress = require('compression');
var layouts = require('express-ejs-layouts');
app.set('layout');
app.set('view engine', 'ejs');
app.set('view options', {layout: 'layout'});
app.set('views', path.join(process.cwd(), '/server/views'));
app.use(compress());
app.use(layouts);
app.use('/client', express.static(path.join(process.cwd(), '/client')));
app.disable('x-powered-by');
var env = {
production: process.env.NODE_ENV === 'production'
};
if (env.production) {
Object.assign(env, {
assets: JSON.parse(fs.readFileSync(path.join(process.cwd(), 'assets.json')))
});
}
app.get('/*', function(req, res) {
res.render('layout', {
env: env
});
});
var port = Number(process.env.PORT || 3001);
app.listen(port, function () {
console.log('server running at localhost:3001, go refresh and see magic');
});
if (env.production === false) {
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var webpackDevConfig = require('./webpack.config.development');
new WebpackDevServer(webpack(webpackDevConfig), {
publicPath: '/client/',
contentBase: './client/',
inline: true,
hot: true,
stats: false,
historyApiFallback: true,
headers: {
'Access-Control-Allow-Origin': 'http://localhost:3001',
'Access-Control-Allow-Headers': 'X-Requested-With'
}
}).listen(3000, 'localhost', function (err) {
if (err) {
console.log(err);
}
console.log('webpack dev server listening on localhost:3000');
});
}
basically i want to declare some variables in php and fetch them to javascript.so just want to add one file in webpack(file named as index.php) and then all my project work normally
Thanks.
You can't run express on the same port of xampp, you have to use different ports (or different servers) to serve the php file.

How can I call localhost from localhost (laravel, nodejs)?

I am writing an application with node and laravel. I am running small laravel local server which resolves to http://localhost:8000. i am also running a node server on localhost:3000. Then trying to call the first server from the second. Here is the NodeJs code:
var restify = require('restify');
var server = restify.createServer();
server.listen(3000, function() {
console.log('%s listening at %s', server.name, server.url);
});
Here is where I make the http request:
var http = require('http');
module.exports = {
call: function (host, path) {
var options = {
host: host,
path: path,
port: 8000,
method: 'GET'
};
callback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
return str;
});
}
http.request(options, callback).end();
}
}
This is the actual call I am making:
httpCaller.call('http://localhost', '/fire');
I get the following response on the command line:
Error: getaddrinfo ENOTFOUND http://localhost http://localhost:8000
at errnoException (dns.js:26:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:77:26)
I tried removing http:// and just calling local host, and got the following:
Error: connect ECONNREFUSED 127.0.0.1:8000
at Object.exports._errnoException (util.js:890:11)
at exports._exceptionWithHostPort (util.js:913:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1057:14)
How can I do this?
Try using the http.get function?
http.get('http://localhost:8000/fire', (res) => {
console.log(`Got response: ${res.statusCode}`);
// consume response body
res.resume();
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});

NodeJs not able to listen to port on digital ocean Ubuntu

I am trying to implement messaging on my server .Which is Ubuntu 14.04/Nginx
I have installed
1.nodejs
2.Redis
3.laravel
all successfully
when I run command
node -v
its giving me the version of node
in my controller my code look like this
public function sendMessage(){
$redis = LRedis::connection();
$redis->publish('message', 'Sending Message to Port');
return redirect('writemessage');
}
and my server.js code is like this
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890);
io.on('connection', function (socket) {
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
console.log("mew message in queue "+ message + "channel");
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
The Redis server is running on default 6379
and to listen to listen to the broadcast my socket.php file has following code
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script>
var socket = io.connect('http://localhost:8890');
socket.on('message', function (data) {
$( "#messages" ).append( "<p>"+data+"</p>" );
});
</script>
Everything is running fine but I don't see any message on the socket.php page
Any Idea how to debug this
the same works fine on Localhost
Update
So I did
redis-cli monitor
and tried to execute my code again I can see redis is broadcasting the messages like this
1458128671.226586 [0 127.0.0.1:59112] "SELECT" "0"
1458128671.232152 [0 127.0.0.1:59112] "PUBLISH" "message" "Sending Message to Port"
but on node side I don't receive it
Please!! help me
Digital Ocean by default close all ports except :80
You need to open the ports first. You can find the solution here
https://stackoverflow.com/a/41408983/4556995

Categories