I have an express backend which includes:
var express = require("express");
var app = express();
var expressWs = require('express-ws')(app);
and:
app.get(/test/, function(req, res){
res.send('{"hello" : "world" }');
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg){
var data = JSON.parse(msg);
if(data.action == "login"){
console.log("logged in!")
}
});
});
I want to be able to close the websocket without closing the app. How do I do this?
ws.close() is what you are looking for
Here it is :
app.get(/test/, function(req, res) {
res.send('{"hello" : "world" }');
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
var data = JSON.parse(msg);
if(data.action == "login"){
console.log("logged in!")
}
});
ws.on('close', function(msg) {
console.log('connection closed...');
});
});
Related
Hello I am trying to build Chat Application, but my issue with socket.io, first
<script src="socket.io/socket.io.js"></script>
is not found, if i am using
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js" integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI" crossorigin="anonymous"></script>
then its working fine for me only one way conection, but
http://127.0.0.1:3000/socket.io/?EIO=4&transport=polling&t=OJDCcA5
this is not found.
Server.js
var express = require('express');
var cors = require('cors');
var mongoose = require('mongoose');
var app = express();
var http = require('http').Server(app);
app.use(cors());
var server = app.listen(3000, () => {
console.log("server is running on port", server.address().port);
});
var io = require('socket.io')(http);
//Connection Mongo Database with Mongooes
var dbUrl = 'mongodb://127.0.0.1:27017/ChatApplication';
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err) => {
if(err){
console.log('Mongodb Not Connected',err);
}
});
var connection = mongoose.connection;
console.log(mongoose.connection.readyState); //logs 0
mongoose.connection.on('connecting', () => {
console.log('connecting')
console.log(mongoose.connection.readyState); //logs 2
});
mongoose.connection.on('connected', () => {
console.log('connected');
console.log(mongoose.connection.readyState); //logs 1
});
mongoose.connection.on('disconnecting', () => {
console.log('disconnecting');
console.log(mongoose.connection.readyState); // logs 3
});
mongoose.connection.on('disconnected', () => {
console.log('disconnected');
console.log(mongoose.connection.readyState); //logs 0
});
connection.once("open", function() {
console.log("MongoDB database connection established successfully");
});
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))
var Message = mongoose.model('message',{ name : String, message : String})
console.log(Message);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/messages', (req, res) => {
console.log("Message Recived");
Message.find({},(err, messages)=> {
res.send(messages);
})
})
app.post('/messages', (req, res) => {
var message = new Message(req.body);
//console.log(message);
message.save((err) =>{
if(err)
sendStatus(500);
io.emit('message', req.body);
res.sendStatus(200);
})
})
io.on('connection', () =>{
console.log('a user is connected')
})
//https://masteringjs.io/mongoose
//https://www.freecodecamp.org/news/simple-chat-application-in-node-js-using-express-mongoose-and-socket-io-ee62d94f5804/
Please let me know, where do i am wrong.
Trying to Real time message get from server end using socket.
I'm fairly new to nodejs, and in wanting to keep the code neat and clean, I tried to extract a function to a different file, and then require it from my main app.
I'm facing a problem that this function includes socket-io data streaming and it uses the http module that uses my express app
This is the main app, and I want to move the content of getDetails to a seperate file:
const express = require('express');
const app = express();
const spawn = require('child_process').spawn;
const execFile = require('child_process').execFile;
const server = require('http').Server(app);
const io = require('socket.io')(server);
// Set router
const router = express.Router();
// fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
router.get('/getDetails', (req, res) => {
const qry = req.query;
if (qry.func === 'tail') {
const tail = spawn('ssh', ['root#' + qry.srv, qry.script, qry.func, qry.serv]);
io.on('connection', function (socket) {
tail.stdout.on('data', function (data) {
socket.emit('newLine', {line: data.toString('utf8').replace(/\n/g, '<br>')});
});
tail.on('close', (code) => {
console.log('child process exited with code', code);
});
tail.stderr.on('data', (data) => {
console.log('There are some errors:', data.toString('utf8'));
socket.emit('newLine', {line: data.toString('utf8')});
});
});
res.sendStatus(200);
}
else {
execFile('ssh', ['root#' + qry.srv, qry.script, qry.func, qry.serv], {timeout: 5000}, (error, stdout, stderr) => {
if (error) {
console.error('stderr', error);
return res.status(500).send({stderr: stderr, error: error});
}
return res.status(200).send({stdout: stdout.toString('utf8')});
});
}
});
app.use('/', router);
server.listen(port, function () {
console.log('The magic happens on localhost:' + port);
});
Now I can module.exports everything on my seperate file but do I need to also require express, and http again?
And should I move the server.listen to the seperate file?
server.js
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const route = require('./route');
// fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())
app.set('socketio', io);
app.use('/',route);
server.listen(port, function () {
console.log('The magic happens on localhost:' + port);
});
route.js
const express = require('express');
const router = express.Router();
const Controller = require('./controller');
router.post('/register',Controller.getDetails);
module.exports=router;
controller.js
const spawn = require('child_process').spawn;
const execFile = require('child_process').execFile;
const controller = {
getDetails : (req,res)=>{
// now use socket.io in your controller file
var io = req.app.get('socketio');
const qry = req.query;
if (qry.func === 'tail') {
const tail = spawn('ssh', ['root#' + qry.srv, qry.script, qry.func, qry.serv]);
io.on('connection', function (socket) {
tail.stdout.on('data', function (data) {
socket.emit('newLine', {line: data.toString('utf8').replace(/\n/g, '<br>')});
});
tail.on('close', (code) => {
console.log('child process exited with code', code);
});
tail.stderr.on('data', (data) => {
console.log('There are some errors:', data.toString('utf8'));
socket.emit('newLine', {line: data.toString('utf8')});
});
});
res.sendStatus(200);
}
else {
execFile('ssh', ['root#' + qry.srv, qry.script, qry.func, qry.serv], {timeout: 5000}, (error, stdout, stderr) => {
if (error) {
console.error('stderr', error);
return res.status(500).send({stderr: stderr, error: error});
}
return res.status(200).send({stdout: stdout.toString('utf8')});
});
}
}
}
module.exports=controller;
I've implemented a websockets api on top of a swagger-express node server.
For websockets I'm using express-ws which utilises the excellent ws library.
However I have come across a problem where the function setInterval is not being called when a websocket client connects.
Confusingly though in the ws.on('connection' function the console.log('websocket connected'); does execute while the setInterval function does not.
Can someone please point out what is wrong with my code?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var expressWs = require('express-ws')(app);
var IndexWS = require('./api/controllers/indexWS');
var config = {
appRoot: __dirname // required config
};
app.ws('/', function(ws, req) {
ws.on('connection', function(conn) {
console.log('websocket connected');
setInterval(function timeout() {
console.log('conn');
}, 500);
});
ws.on('close', function() {
console.log('The connection was closed!');
});
ws.on('error', function() {
console.log('websocket error!');
});
ws.on('message', function(msg) {
setTimeout(function timeout() {
ws.send("500 delay");
}, 500);
});
console.log('websocket connected');
});
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 3030;
app.listen(port, '0.0.0.0');
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('server running on port ' + port );
}
});
I have a node WebServer capable of communicating with Browser(say browserInstance) and linux terminal(say ProxyInstance) via Websockets. The job of the webserver is to handover the data from terminal to WebBrowser and vice-verse. Please find the server.js code below:
var express = require('express');
var expressWs = require('express-ws');
var expressWs = expressWs(express());
var app = expressWs.app;
var appForpage = express();
var browserInstance;
var ProxyInstance;
var browserCounter = 0;
var ProxyCounter = 0;
app.ws('/fromBrowser', function(ws, req, next) {
console.log("~~~~~~~~~~~~BROWSER");
if(browserCounter == 1){
ws.on('message', function(msg) {
console.log("Messagae from Browser :", msg);
ProxyInstance.send(msg);
});
}else{
browserInstance = ws;
ws.on('message', function(msg) {
console.log("Message from Browser :", msg);
ProxyInstance.send(msg);
});
browserCounter = 1;
}
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
app.ws('/fromProxy', function(ws, req, next) {
console.log("~~~~~~~~~~~~PROXY");
if(ProxyCounter == 0){
ProxyInstance = ws;
ProxyCounter = 1;
}else if(browserCounter == 1){
ws.on('message', function(msg) {
console.log("Message from Proxy: ", msg);
browserInstance.send(msg);
});
}
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
appForpage.use(express.static(__dirname + '/public/')); // index.html resides in public directory
appForpage.listen(5000)
app.listen(3000)
First I am creating ws connection from proxy to webserver(/fromProxy) and then from browser(/fromBrowser). The connection was successfully created. When i try to send data from Browser to proxy via Webserver, it works fine. In return to the 1st message at proxy end when tries to communicate Browser via WebServer, this one failed. I haven't received any message from Proxy. I need to run the respective ends in the same order(Proxy first and then Browser..).
I am just beginner to node. I haven't find any example over internet for my case. What am I missing here ?
That's really silly :( .I haven't registered my messsage callback from proxy. Please find the working code below.
var express = require('express');
var expressWs = require('express-ws');
var expressWs = expressWs(express());
var app = expressWs.app;
var appForpage = express();
var browserInstance;
var ProxyInstance;
var browserCounter = 0;
var ProxyCounter = 0;
app.ws('/fromBrowser', function(ws, req, next) {
console.log("~~~~~~~~~~~~BROWSER");
if(browserCounter == 1){
ws.on('message', function(msg) {
console.log("Messagae from Browser :", msg);
ProxyInstance.send(msg);
});
}else{
browserInstance = ws;
ws.on('message', function(msg) {
console.log("Message from Browser :", msg);
ProxyInstance.send(msg);
});
browserCounter = 1;
}
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
app.ws('/fromProxy', function(ws, req, next) {
console.log("~~~~~~~~~~~~PROXY");
if(ProxyCounter == 0){
ProxyInstance = ws;
ProxyCounter = 1;
}
/*This is the place where i went wrong. damnn..*/
ws.on('message', function(msg) {
console.log("Message from Proxy: ", msg);
browserInstance.send(msg);
});
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
appForpage.use(express.static(__dirname + '/public/')); // index.html resides in public directory
appForpage.listen(5000)
app.listen(3000)
I'm trying to create a dummy socket for use in some of my tests
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.write("hello!");
Getting this error
Error: This socket is closed.
I've also tried creating the socket with
var s = new net.Socket({allowHalfOpen: true});
What am I doing wrong?
For reference, the complete test looks like this
it("should say hello on connect", function(done) {
var socket = new net.Socket();
var client = Client.createClient({socket: socket});
socket.on("data", function(data){
assert.equal("hello", data);
done();
});
client.connect();
// writes "hello" to the socket
});
I don't think the server is put into listening state. This what I use..
// server
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString());
});
})
.listen(8080);
// client
var s = require('net').Socket();
s.connect(8080);
s.write('Hello');
s.end();
Client only..
var s = require('net').Socket();
s.connect(80, 'google.com');
s.write('GET http://www.google.com/ HTTP/1.1\n\n');
s.on('data', function(d){
console.log(d.toString());
});
s.end();
Try this.
The production code app.js:
var net = require("net");
function createSocket(socket){
var s = socket || new net.Socket();
s.write("hello!");
}
exports.createSocket = createSocket;
The test code: test.js: (Mocha)
var sinon = require('sinon'),
assert = require('assert'),
net = require('net'),
prod_code=require('./app.js')
describe('Example Stubbing net.Socket', function () {
it("should say hello on connect", function (done) {
var socket = new net.Socket();
var stub = sinon.stub(socket, 'write', function (data, encoding, cb) {
console.log(data);
assert.equal("hello!", data);
done();
});
stub.on = socket.on;
prod_code.createSocket(socket);
});
});
We can create socket server using net npm module and listen from anywhere. after creating socket server we can check using telnet(client socket) to interact server.
server.js
'use strict';
const net = require('net');
const MongoClient= require('mongodb').MongoClient;
const PORT = 5000;
const ADDRESS = '127.0.0.1';
const url = 'mongodb://localhost:27017/gprs';
let server = net.createServer(onClientConnected);
server.listen(PORT, ADDRESS);
function onClientConnected(socket) {
console.log(`New client: ${socket.remoteAddress}:${socket.remotePort}`);
socket.destroy();
}
console.log(`Server started at: ${ADDRESS}:${PORT}`);
function onClientConnected(socket) {
let clientName = `${socket.remoteAddress}:${socket.remotePort}`;
console.log(`${clientName} connected.`);
socket.on('data', (data) => {
let m = data.toString().replace(/[\n\r]*$/, '');
var d = {msg:{info:m}};
insertData(d);
console.log(`${clientName} said: ${m}`);
socket.write(`We got your message (${m}). Thanks!\n`);
});
socket.on('end', () => {
console.log(`${clientName} disconnected.`);
});
}
function insertData(data){
console.log(data,'data');
MongoClient.connect(url, function(err, db){
console.log(data);
db.collection('gprs').save(data.msg , (err,result)=>{
if(err){
console.log("not inserted");
}else {
console.log("inserted");
}
});
});
}
using telnet:
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
We got your message (hi). Thanks!
you need to connect your socket before you can write to it:
var PORT = 41443;
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.connect(PORT, function(){
s.write("hello!");
});
It will useful code for websocket
'use strict';
const express = require('express');
const { Server } = require('ws');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = process.env.PORT || 5555;
const INDEX = '/public/index.html';
const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
router.get('/', function(req, res) {
res.sendFile(INDEX, { root: __dirname });
});
const server = express()
.use(router)
.use(bodyParser.json())
.use(cors)
.listen(PORT, () => {
console.log(`Listening on ${PORT}`)
});
const wss = new Server({ server });
wss.on('connection', (ws) => {
ws.on('message', message => {
var current = new Date();
console.log('Received '+ current.toLocaleString()+': '+ message);
wss.clients.forEach(function(client) {
client.send(message);
var getData = JSON.parse(message);
var newclip = getData.clipboard;
var newuser = getData.user;
console.log("User ID : "+ newuser);
console.log("\nUser clip : "+ newclip);
});
});
});