Client program for continuous talking to an echo server in nodejs - javascript

I'm an absolute beginner in nodejs. I've created an echo server in nodejs. And honestly i would say, i followed few youtube tutorials for this. There is nothing wrong with the server code. I want to create a client program to talk to this server. I dont want to use telnet client or any such thing. And by 'continuous' I mean the server and client should stay connected till I close the server manually using ctrl+c. Here's my server.js.
const express = require('express');
const bodyParser=require('body-parser');
var server=express();
server.use(bodyParser.urlencoded({extended: false}));
server.use(bodyParser.json());
server.post("/", function (req, res) {
console.log("I got: "+req.body.message);
res.send(req.body.message);
});
server.listen(3000, function() {
console.log("Express echo server is listening on port 3000");
})
I do not say hey write the code for me. In fact I tried also. Here's my client.js
var request = require('request');
var arg="";
process.argv.slice(2).forEach(function (val, index, array) {
arg+=val +" ";
});
request.post({
url: "http://localhost:3000",
json: true,
body: {message: arg}
}, function (err, response, body) {
if(!err && response.statusCode==200) {
console.log(body);
}
});
But client sends data only once that too using command line argument.
node client.js hello
PS: I'm using these npm modules express, body-parser and request

What you made is a HTTP Server using express.
The server runs alright, but the client closes because you are only making a single request to the server. So what is happening is expected behaviour.
So, there are multiple ways,
The most simple way would be, using readline or some other to continuously read the lines that you type And sending it to the server:
const request = require('request');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
readline.setPrompt('msg: ');
readline.prompt();
readline.on('line', function(input) {
if(input === 'close') return readline.close();
request.post({
url: "http://localhost:3000",
json: true,
body: {message: input}
}, function (err, response, body) {
readline.prompt();
});
}).on('close', function() {
console.log('Closed');
process.exit(0);
});
But the proper way would be using sockets like socket-io to make a persistent connection between the server and client. Read here for more information.

Related

Return image using API - Pure NodeJS (no Express)

I am trying to return an image when a user connects to the server ip address, in short, create an API that returns an image.
I had found this solution that worked however now I don't know why it doesn't work.
I don't want to use Express or similar.
UPDATE
Without res.end() it works, but I don't understand why.
import http from 'http';
import mime from 'mime';
import fs from 'fs';
const hostname = '127.0.0.1';
const port = 8000;
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': mime.getType('./tmp/screenshot.png') });
fs.createReadStream('./tmp/screenshot.png').pipe(res);
res.end();
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
in:
fs.createReadStream('./tmp/screenshot.png').pipe(res);
you already add a pipe to send data between the server and the client and after finishing sending data, it automatically triggers the end() event.
if you don't want this behavior. just do this
fs.createReadStream('./tmp/screenshot.png').pipe(res, {end:false});
I hope it's help you :)

How to get JSON data from node.js to HTML

I am trying to create a web app with some drop down menus that contain data from a sql server database. After some searching I figured out how to use node.js to output the table data into the command prompt.
var sql = require('mssql/msnodesqlv8');
var config = {
connectionString: 'Driver=SQL Server;Server=NAME\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
new sql.Request().query('SELECT * FROM TABLE', (err, result) => {
console.log("Works");
if(err) { // SQL error, but connection OK.
console.log(" Error: "+ err);
} else { // All good.
console.dir(result);
};
});
});
sql.on('error', err => { // Connection bad.
console.log("Bad");
console.log(" Error: "+ err);
});
Now the problem is I don't know how to get that result into JSON data that can be used in my web app. Any help would be appreciated as I am quite new to node.js. Thanks!
EDIT:
Thanks for the help so far! I added the following code for when there is no error:
var express = require('express')
var app = express()
JSON.stringify(result);
console.log(JSON.stringify(result));
app.get('/', function (req, res) {
res.send(result)
})
I also have all of the code for the http server but I don't think it's necessary to show it all. Is this all that is needed on the server side?
First of all, to send data from the server to the client you'll have to run an HTTP server as part of your Node backend. Then, once the web app loads, it should make a request to your server, which as a response will return the data from the database. For more information on how to do this check out Express (for the server side) and Fetch API (for the client side).

How to check if WebSocket.server connection is open or closed?

Im using node js and I cant figure out how to check if my WebSocket.Server connection is Open or Closed, is there any function like socket.readyState?
Im asking because I have a problem, when me + someone else reloads the 192....../xxx in the same moment I get an error Error: listen EADDRINUSE :::3001 and I cant figure out where it blows up..
Also Id like to mention that I DO close the connection but only in one spot, here is my code example;
router.get('/', function(req, res, next) {
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('Client: Im on... /zzz');
})
});
wss.on('error', function error(err) {
console.log(wss.clients);
next(err);
});
//??
//wss.clients.clear();
db.all('SELECT rowid, * FROM ZZZZZZZZ', (err, rows) => {
//idk if its ok
if (err) next(err);
if (rows.length == 0) {
res.render('xxxxx/index', {
AAA: 'empty'
});
} else {
wss.close(function(err) {
if (err) next(err);
console.log('closing websocket at /zzz');
server.close();
setTimeout(function() {
wss = new WebSocket.Server({
port: 3001
});
}, 100);
});
res.render('xxx/index', {
AAA: rows
});
}
});
});
And heres what I have above my router.get
let express = require('express');
let router = express.Router();
let sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./xx/xx/xx/xxx/xx/xxx.db');
let WebSocket = require('ws');
let wss = new WebSocket.Server({ port: 3001 });
let server = wss._server;
Looks to me like you have the websocket server depend on a specific endpoint. The error you're getting is trying to tie multiple websocket servers to the same port. You only really need one websocket server to handle multiple client connections. I suggest that you would make them separate and have the websocket server run alongside of the express app.
Having endpoints to perform certain actions like closing the websocket is cool, but I would suggest authenticating them if you're doing something like that.
The error you are having is 100% server side, port 3001 is in use. It's trying to start up a websocket server on port 3001 and there is already one running. You can either use different ports, or just use the original websocket server to serve multiple clients.
To actually answer the question you asked, I believe the proper way for doing so would be to implement a heartbeat for your websocket server. That should send after n amount of minutes/seconds/milliseconds (I'd probably go with minutes). It's a good idea to have it bidirectional so your server and clients know when a connection has been dropped.

Send data from websocket to socket.io

I used websocket interface to connect to websocket server . what if i want send data that i receive from the websocket server through my websocket interface to client connected to me through http server , should i use socket.io ?
so at the end i will have socket.io attached to to http server and websocket interface to get data and in case of message come will be send to client through socket.io . is that the best setup ?
Code Example :
// Require HTTP module (to start server) and Socket.IO
var http = require('http'),
io = require('socket.io');
var WebSocket = require('ws');
var ws = new WebSocket('ws://localhost:5000');
// Start the server at port 8080
var server = http.createServer(function (req, res) {
// Send HTML headers and message
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function (data, flags) {
// here the data will be send to socket.io
});
// Add a connect listener
socket.on('connection', function (client) {
// Success! Now listen to messages to be received
client.on('message', function (event) {
console.log('Received message from client!', event);
});
client.on('disconnect', function () {
clearInterval(interval);
console.log('Server has disconnected');
});
});
Yes, your design is correct.
However, one thing that you should keep in mind is take care of sending the message to the correct client after authentication. In my opinion, it is very easy to make this mistake, partially because of the simplicity of messaging using websockets.

Request data using jQuery from a NodeJS server

I have the following client code (that runs in a browser or atom-shell/node-webkit Web API):
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1:1337/users',
type: 'GET',
dataType: 'json',
success: function(res)
{
console.log(res);
}
});
});
Pretty simple stuff, it requests a list of users in JSON format from a server.
Now on the server end (Node API) I have the following code:
var http = require('http');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'admin',
password : 'qwe123'
});
// Create the server
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('This is just a placeholder for the index of the server.');
}).listen(1337, '127.0.0.1');
// Build a response
http.get('http://127.0.0.1:1337/users', function(res) {
var json = { 'status' : res.statusCode, 'response' : res };
JSON.parse(json);
}).on('error', function(e) {
var json = { 'status' : e.statusCode, 'message' : e.message };
JSON.parse(json);
});
I've become confused as how to create the server and then effectively create endpoints (e.g. /users) that I can talk to via my client code.
1.) Am I right in thinking that http.get only gets data from an already established endpoint? And that createSever actual creates the endpoints? Or is there another shorthand method for creating these endpoints after the server has been created? So basically that get request isn't required in this example as I am wanting to request it client side.
2.) In any case I need to create this endpoint /users and return the following:
connection.connect();
connection.query('SELECT * FROM users', function(err, results) {
JSON.parse(results);
});
connection.end();
Can anyone help point me back in the right direction? Seems like I've missed that part in the docs where you can create the different endpoints on your server.
I am afraid you are mixing expressjs and node http module. If you are just using node "http", refer this: Nodejs to provide 1 api endpoint e one html page on how to achieve the routing of URL's.
All said, i would suggest you to take a look at the library expressjs for this: http://expressjs.com/starter/basic-routing.html. It largely simplifies the route management and provides much more functionality.
Hope this helps you.

Categories

Resources