I'm building a forum where two users after connections can post a status then comment on them.
For comments, i used socket.io .
In console i'm getting this error each few seconds :
Failed to load resource: net::ERR_CONNECTION_REFUSED
GET http://localhost/socket.io/?EIO=4&transport=polling&t=O05nump net::ERR_CONNECTION_REFUSED
How to fix this error ?
I installed express, nodemon and socket.io in my socket server:
Socket server:
package.json
{
"name": "socket",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.3",
"nodemon": "^2.0.15",
"socket.io": "^4.4.1"
}
}
app.js
const io = require("socket.io")(4000, {
cors: {
origin: "http//localhost:3000",
},
});
io.on('connection', (socket) => {
console.log('A new user is connected !');
})
io.on('disconnect', () => {
console.log('User has left !');
});
Front:
Also, i installed socket.io-client in client (front), then in my web page, i added this code :
import { io } from 'socket.io-client'
export default () => {
//implement socket
const socket = useRef()
useEffect(() => {
socket.current = io("ws://localhost/4000")
}, [])
return (
//some html code
)
}
My project tree:
Project Forum
├── back
├── client
└──index.jsx
└── socket
└──package.json
└──app.js
Console Visual Studio Code:
Visual studio code's console shows this only how many times i refresh browser or ctrl+S the code:
[nodemon] starting 'node apde app.js'
You added a slash instead of semi-colon:
socket.current = io("ws://localhost:4000")
const socketio = require("socket.io");
const express = require("express");
const http = require("http");
const app = express();
const PORT = process.env.PORT || 2018;
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: "*",
methods: ["GET", "POST", "OPTIONS"]
}
});
server.listen(PORT, () => {
io.on("connection", socket => {
console.log("ok");
console.log(socket.id);
// io.in(roomID).emit()
socket.emit("WELCOME_MESSAGE", ` ${socket.id} welcome!! `);
});
});
Related
Making a GET request to my own authenticating user users/{id}/tweets in nodeJS and using V2 Twitter api, returns only tweets posted by my own authenticating user id.
What I need?
To GET all tweets both posted by myself and the ones that are showing in my timeline from users I follow.
Basically, the same result as in Twitter V1 GET statuses/home_timeline
How can I get this in V2?
index.js
const express = require("express");
const app = express();
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(express.json()); // for parsing application/json
const Twit = require("twitter-lite");
const config = require("./config");
const client = new Twit(config.appConfig);
function getTimeLineTweetsInV2() {
return new Promise(async (resolve, reject) => {
try {
let result = await client.get("users/tweets/1497521946694717448");
resolve(result);
} catch (error) {
console.log("errorrrrrrrrrr is", error);
reject(error);
}
});
}
(async function BotMain() {
let tweetsReceived = await getTimeLineTweetsInV2();
console.log(tweetsReceived);
})();
app.listen(3000, () => {
console.log("listeing on port 3000");
});
config.js
const dotenv = require("dotenv");
const path = require("path");
const ENV_FILE = path.join(__dirname, ".env");
dotenv.config({ path: ENV_FILE });
const appConfig = {
//define subdomain of twitter api URL e.g. api.twitter.com, streams.twitter.com
version: "2",
extension: false,
consumer_key: process.env.apikey,
consumer_secret: process.env.apisecret,
access_token_key: process.env.accesstoken,
access_token_secret: process.env.accesstokensecret,
};
module.exports = {
appConfig,
};
package.json
{
"name": "twitter_app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.0",
"express": "^4.17.3",
"path": "^0.12.7",
"twitter-lite": "^1.1.0"
}
}
There is no equivalent to the home timeline API in v2 - yet. This is on the roadmap. You’ll need to use the v1.1 API, or, be patient until a new version is available.
I created a chat room using socket.io within my express app and it's working fine in local host
when I deployed my application to heroku I get this error when I open the chat room
GET http://localhost:5000/socket.io/?EIO=3&transport=polling&t=N1PV-tt net::ERR_CONNECTION_REFUSED
here is my index.js file
var express = require("express")
var cors = require("cors")
var bodyParser = require("body-parser")
var app = express()
var mongoose = require("mongoose")
//var http = require('http').createServer(app);
var io = require('socket.io')(http)
var port = process.env.PORT || 5000
var server = app.listen(port);
var io = require('socket.io').listen(server);
var http = require('http');
let users = [];
let messages = [];
let index = 0;
app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
const mongoURI = 'mongodb+srv://1920:1920#cluster0-qyzs9.mongodb.net/liebherr?retryWrites=true&w=majority'
mongoose.connect(mongoURI, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err))
var Users = require("./routes/Users")
app.use("/users", Users)
//Socket connection
io.on('connection', (socket) => {
io.emit('noOfConnections', Object.keys(io.sockets.connected).length)
socket.on('disconnect', () => {
console.log(`a user has left the chat.`);
io.emit('noOfConnections', Object.keys(io.sockets.connected).length)
})
socket.on('chat-message', (msg) => {
socket.broadcast.emit('chat-message', msg)
})
socket.on('typing', (data) => {
socket.broadcast.emit('typing', data)
})
socket.on('stoptyping', () => {
socket.broadcast.emit('stoptyping')
})
})
// Static folder
app.use(express.static(__dirname + '/public/'));
app.get(/.*/);
and here is package.json file
{
"name": "express-demo",
"version": "1.0.0",
"description": "This is a full stack application",
"engines": {
"node": "13.1.0"
},
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"author": "Farouk Turki",
"license": "ISC",
"dependencies": {
"bcrypt": "^3.0.7",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongodb": "^3.5.2",
"mongoose": "^5.8.9",
"nodemon": "^2.0.2",
"socket.io": "^2.3.0"
}
}
Everything is working fine except the chatroom so I need to know why it's still using port 5000 in localhost
From the front end (socket.io client) you are setting the hostname as localhost. But a front end code is not run server-side, it is in client side(your browser/or any thin client), it can access only the resources that are accessible over the internet(or the resources which is accessible by the browser itself).
So, in your case, the connection code will look something like:
<script>
const socket = io('http://<your-heroku-public-url-for-the-express-server>');
// which typically is
const socket = io('http://randomname.herokuapp.com');
</script>
Given that http://randomname.herokuapp.com is the public url of your node js server.
I'm trying to write a simple WebSocket server app based in Nodejs, but I am unable to get it started when I run npm run dev.
This is my package.json file:
"name": "lg-chain",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --watchAll",
"dev-test": "nodemon dev-test",
"start": "node ./app",
"dev": "nodemon ./app"
},
"keywords": [],
"license": "MIT",
"devDependencies": {
"jest": "24.1.0",
"nodemon": "1.18.9"
},
"dependencies": {
"body-parser": "1.18.3",
"crypto-js": "3.1.9-1",
"express": "4.16.4",
"ws": "6.1.3"
}
}
I developed both an http server and websocket server and my expectation is that they both will start when I run that command I mentioned above.
Below is my websocket server:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
class P2pServer {
constructor(blockchain) {
this.blockchain = blockchain;
this.sockets = [];
}
listen() {
const server = new Websocket.Server({ port: P2P_PORT });
server.on('connection', socket => this.connectSocket(socket));
this.connectToPeers();
console.log(`Listening for peer-to-peer connections on: ${P2P_PORT}`);
}
connectToPeers() {
peers.forEach((peer) => {
const socket = new Websocket(peer);
socket.on('open', () => this.connectSocket);
});
}
connectSocket(socket) {
this.sockets.push(socket);
console.log('Socket connected');
}
}
module.exports = P2pServer;
And this is my express server:
const express = require('express');
const bodyParser = require('body-parser');
const Blockchain = require('../blockchain');
const P2pServer = require('./p2p-server');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
const bc = new Blockchain();
const p2pServer = new P2pServer(bc);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/blocks', (req, res) => {
res.json(bc.chain);
});
app.post('/mine', (req, res) => {
const block = bc.addBlock(req.body.data);
console.log(`New block added: ${block.toString()}`);
res.redirect('/blocks');
});
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();
My express server starts up, but absolutely nothing happens with my websocket server. I don't get any errors anywhere. How do I begin troubleshooting this with websockets?
I'm taking an online course on writing block-chain from scratch.
The course utilizes javascript and node.js.
I am very new to these technologies but followed the course so far to the T.
i'm pasting the relevant code - the app file (index):
const express = require('express');
const bodyParser = require('body-parser');
const Blockchain = require('../blockchain');
const P2pServer = require('./p2p-server');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
const bc = new Blockchain();
const p2pServer = new P2pServer(bc);
app.use(bodyParser.json());
app.get('/blocks', (req, res) => {
res.json(bc.chain);
});
app.post('/mine', (req, res) => {
const block = bc.addBlock(req.body.data);
console.log(`New blovk added: ${block.toString()}`);
res.redirect('/blocks');
});
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();
and the code from p2p-server.js:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
//HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
class P2pServer {
constructor(blockchain) {
this.blockchain = blockchain;
this.sockets = [];
}
listen() {
const server = new Websocket.Server({ port: P2P_PORT });
server.on('connection', socket =>this.connectSocket(socket));
this.connectToPeers();
console.log(`listening to peer-to-peer connections on: ${P2P_PORT}`);
}
connectToPeers() {
peers.forEach(peer => {
const socket = new Websocket(peer);
socket.on('open', () => this.connectSocket(socket));
});
}
connectSocket(socket){
this.sockets.push(socket);
console.log('socket connected');
}
}
module.exports = P2pServer;
when I try to run the following in the command line:
HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
I get the following:
'HTTP_PORT' is not recognized as an internal or external command, operable program or batch file.
for some reason the process.env isn't picking up the input and passing it on to the app. What is wrong here?
Thanks!
EDIT: I was asked to add the package.json:
{
"name": "sf-chain",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --watchAll",
"dev-test": "nodemon dev-test",
"start": "node ./app",
"dev": "nodemon ./app"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^23.1.0",
"nodemon": "^1.17.5"
},
"dependencies": {
"body-parser": "^1.18.3",
"crypto-js": "^3.1.9-1",
"express": "^4.16.3",
"ws": "^5.2.0"
}
}
You are using:
$ HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
It is showing an error, because the window powershell will not recognize this command..
Instead you should use:
set HTTP_PORT=3002 && set P2P_PORT=5002 && set PEERS=ws://localhost:5001 && npm run dev
I believe were doing the same course. I'm sure you've probably figured this out but I tried the same step in Git Bash instead of Powershell and it worked.
I have 3 files :
server.js containing node.js server (Using WebSocket-Node)
client.js containing websocket code
frontend.html containing the html content includes the client.js file.
package.json :
{
"name": "kapp",
"version": "1.0.0",
"description": "Lightweight peer to peer",
"main": "frontend.html",
"scripts": {
"test": "node server.js"
},
"engines": {
"node": "0.10.x"
},
"author": "Kaustav Ray",
"license": "MIT",
"dependencies": {
"websocket": "^1.0.19"
}
}
server.js
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
});
server.listen(1337, function() { });
wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
if (message.type === 'utf8') {
}
});
connection.on('close', function(connection) {
});
});
client.js
$(function () {
window.WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://127.0.0.1:1337');
connection.onopen = function () {
};
connection.onerror = function (error) {
};
connection.onmessage = function (message) {
try {
var json = JSON.parse(message.data);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message.data);
return;
}
// handle incoming message
};
});
Local Folder Structure:
.git
node_modules // containing websocket
client.js
frontend.html
server.js
package.json
But somehow my application is not running and showing application error !
I want to first start the nodejs server and open frontend.html.
As I am starting with nodejs and heroku for first time cannot understand the exact problem !
Is there a problem in routing or other things are causing this error ?
Is express.js mandatory for routing ?
Heroku requires that your either provide a Procfile, which is a simple file that tells Heroku how to actually start your app, or specify scripts.start in your package.json.
// Procfile
web: node server.js
// package.json
"scripts": {
"start": "node server.js"
},
https://devcenter.heroku.com/articles/nodejs-support#default-web-process-type
https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction