I have a simple, local Nodejs server running Express. I'm using express-ws to set up a WebSocket endpoint. The client sends messages fine, and the server receives them, but when the server tries to send a message back, the connection closes and the client never receives the message.
This only happens over port 80. The connection stays open over port 3000, 8080, 443, and the client receives the messages the server sends back.
app.js
const express = require('express');
const path = require('path');
const app = express();
const expressWs = require('express-ws')(app);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next){
res.send(`<script src="js/client.js"></script>`);
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
ws.send(msg); //The connection doesn't close with this commented out
});
});
app.listen(80);
client.js
const ws = new WebSocket(`ws://${window.location.host}`);
ws.onopen = function(e){
console.log("WebSocket connected");
ws.send("testing 1");
ws.send("testing 2");
}
ws.onmessage = function(msg){
console.log(msg);
}
I'm at a loss. Any help would be appreciated.
Related
Scenario: Creating a Node API (GET) calling that API in socket.io Node server and calling this socket server in angular client.
What i have done: Created a node API for get request and post and created a socket server I tried to consume the app.
Issues: 1. I tried to consume the API but was unable to get the data in the socket server and 2. If it works, also how can i get the socket data on button click in angular application?
Note: I'm running Node API on 3000 server and running socket server on 3001.
Below is my code
Node api code runnning on 3000 port:
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express()
const port = 3000
let books = [{
"isbn": "9781593275846",
"title": "Eloquent JavaScript, Second Edition",
"author": "Marijn Haverbeke",
"publish_date": "2014-12-14",
"publisher": "No Starch Press",
"numOfPages": 472,
}];
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/book', (req, res) => {
const book = req.body;
// output the book to the console for debugging
console.log(book);
books.push(book);
res.send('Book is added to the database');
});
app.get('/book', (req, res) => {
res.json(books);
});
app.listen(port, () => console.log(`Hello world app listening on port ${port}!`));
Socket .io server running on 3001
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
const apiUrl="http://localhost:3000/book"
io.on('connection', function (socket) {
socket.on('getBanners', function(data){
request.get(apiUrl,function (error, response, body){
console.log(body)
socket.emit('result', {res:JSON.parse(body)})
})
});
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
Note: Node API server --> socketio server (not client)
I wouldn't recommend going by that design you have.
Unless there is a very specific/important reason to have the socket.io server on a different port than the HTTP server, I would recommend having your socket.io server upgraded from the HTTP server itself.
eg.
In bin/www:
const { initSocketIOServer } = require('../socket-server');
const port = normalizePort(process.env.PORT || '3001');
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
initSocketIOServer(server);
In socket.server.js
module.exports.initSocketServer = (server) => {
io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('client connected');
socket.on('getBanners', (event) => {
// handle getBanners event here
});
});
};
However, going by your example, if you really need to make a request to the HTTP server to fetch data, you might want to use the HTTP library:
socket.on('getBanners', (event) => {
http.get({
hostname: 'localhost',
port: 3000,
path: '/book',
agent: false // Create a new agent just for this one request
}, (res) => {
// Do stuff with response, eg.
const socketResponse = processBooks(book);
socket.emit('result', socketResponse);
});
});
You can use any node package for requests like request https://github.com/request/request
here
I've been trying to create an app that uses telegram-bot, express server and react app. Therefore, I need to create a POST request from telegram-bot to express, while express sends POST data to a websocket connection:
const express = require("express");
const app = express();
const expressWs = require("express-ws")(app);
// handles bot request
app.post("/request", (req, res) => {
playlist.push(req.body.url);
res.status(200).send({ message: "video is added to playlist" });
});
// after handling requst data must go here and send ws message to client side
app.ws("/echo", (ws, req) => {
ws.on("message", msg => {
ws.send(`msg is = ${msg}`);
});
});
Am I making it right, and if so, how to call ws.send from after handling request at app.post route?
From the understanding I have from your question, here is an updated version of your code that does exactly what you want.
I replaced the express-ws package with ws since that would be sufficient for your use case.
The express server runs on port 8080 while the websocket server runs on port 8081 since are different protocols and would not run on the same port (You can make it work but I do not recommend it See this question
const express = require("express");
const Websocket = require('ws');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const wss = new Websocket.Server({ port: 8081 });
wss.on('connection', (ws) => {
console.log('One client connected');
ws.on("message", msg => {
ws.send(`msg is = ${msg}`);
});
})
// handles bot request
app.post("/request", (req, res) => {
// Broadcast URL to connected ws clients
wss.clients.forEach((client) => {
// Check that connect are open and still alive to avoid socket error
if (client.readyState === Websocket.OPEN) {
client.send(url);
}
});
res.status(200).send({ message: "video is added to playlist" });
});
app.listen(8080, () => {
console.log('Express listening on 8080');
console.log('Websocket on 8081');
});
Tested via curl with curl -d 'url=https://example.com/examplesong' localhost:8080/request I had a client connected to ws://localhost:8081 and everything looks good.
I am trying to connect my front-end which is on a online text editor to my Node server. I am hitting network error strict-origin-when-cross-origin and it is not hitting the Socket IO listener. Please let me know what is causing this error & how to fix it. Thanks!
Here is the Node.js code:
const cors = require('cors');
const app = express();
app.options('*', cors())
app.all('*', function(req, res) {
res.send("Oops, incorrect URL")
});
const server = http.createServer(app).listen(process.env.PORT, () => {
console.log('Express server listening on port 1337');
});
var io = require('socket.io')(server);
io.set('origins', '*:*');
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
console.log("CONNECTED!")
});
Here is the front-end:
import io from 'socket.io-client'
var socket = io('https://myserver.com/', {secure: true});
socket.emit('chat message', "testing");
I am trying to connect to a socket.io-client using this as my server.js:
var express = require('express');
var app = express();
var server = app.listen(3001);
var io = require('socket.io').listen(server);
app.get('/input', function(req, res){ // This is because in the server the port 3001 is open and I only can use the route 'input' to connect to the node server
res.send('Hello world');
});
io.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
And in my client file:
var socket = io.connect('https://urlofthepage:3001', {reconnect: true});
socket.on('connect', function() { console.log('connect'); });
// or (I tried with both)
var socket = io.connect('https://urlofthepage:3001/input', {reconnect: true});
socket.on('connect', function() { console.log('connect'); });
But when I go to urlofthepage/input show me
Hello world
but in the node server not show anything like
Client connected.
And in the page where I have the client.js file the console show me
3001/socket.io/?EIO=3&transport=polling&t=MBSSeZj net::ERR_CONNECTION_TIMED_OUT
Edit: It's on an online server, which has a wordpress installed, and my socket.io.js script is urlofpage/socket.io/socket.io.js
AND (I don't know if this matters, it is a test server, and the url has https, but it indicates that it is not secure, we have to change it)
I'm trying to implement socket.io on my server. This server is an API (express nodejs).
The server side is simple, but for the client side I'm using phonegap/cordova.
I don't use a phone to test what I do, I use my browser (chrome).
Si this the server side :
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
for now, this is simple,
But for the client side I am completely confuse (cordova phonegap),
This is what I have :
index.html
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
console.log('send')
socket.emit('my other event', { my: 'data' });
});
</script>
Nothing appears but errors like
GET http://localhost:8080/socket.io/?EIO=2&transport=polling&t=1462638049681-3 net::ERR_CONNECTION_REFUSED
and nothing on my server
any ideas to help me ? thanks :)
Your server is not listening on port 8080. That's why when you try to connect from browser to var socket = io.connect('http://localhost:8080');, it shows 'Connection Refused'.
This edit would work for you.
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
//Now server would listen on port 8080 for new connection
http.listen(8080, function(){
console.log('listening on *:8080');
});