Node JS/ Socket.IO - Receive only over TCP/IP [duplicate] - javascript

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);
});
});
});

Related

How can I send request from server to other clients and receive response from clients and then send data in node.js?

I am building a blockchain application, where I send a request from the server to the clients that the server wants to add a block on the chain, if all the clients approve the request, the server will add a block to the chain. Here are my codes.
Server.js
const express = require('express');
const app = express();
const http = require('http').createServer();
var port = 3000;
const io = require('socket.io')(http);
const io2 = require('socket.io-client');
const io3 = require('socket.io-client');
//const io4 = require('socket.io')(http);
const fs = require('fs');
var block = require('./blockchain');
var count = 0;
var bcdata = {};
let socket2 = io2.connect("http://localhost:3001");
socket2.on('client12other', (data)=>{
console.log("Data Received from Client: ", data);
if(data == "Client-1: Approved"){
count++;
}
});
let socket3 = io3.connect("http://localhost:3002");
socket3.on('client22other', (data)=>{
console.log("Data Received from Client: ", data);
if(data == "Client-2: Approved"){
count++;
}
});
io.on("connection", (socket) => {
socket.emit("server2client","Need Approval");
console.log("Receiver Connected ");
});
http.listen(port, () => {
console.log("Server is up at port: "+port);
setTimeout(a, 2000);
//a();
});
//console.log("End of File");
function a(){
console.log("Inside function a");
let data = blockAdd();
if(data != null){
io.on("connection", (socket) => {
socket.emit("sendblock",bcdata);
console.log("BC Sent! ");
});
}
else{
console.log("Data is null");
}
}
function blockAdd(){
if(count == 0){
block.blockAdd({FileName: "Anyfile", Author:"Sowvik",TimeStamp:"1/1/2021", Size:"500MB", Hash:"dsjfoiJKLJSLKJhflkzxnl85290sjdJFDSKL",Extension: ".mp3"});
block.blockAdd({FileName: "Test File", Author:"Mushfiq",TimeStamp:"1/5/2023", Size:"750MB", Hash:"dfgdgdfgdfsdvdfgnee534",Extension: ".ransomware"})
block.blockAdd({FileName: "Movie", Author:"Test",TimeStamp:"1/1/2021", Size:"500MB", Hash:"dfhhKHWDQIowieyoy(*Y*(y0394L", Extension: ".txt"})
//block.printBlockchain();
bcdata = block.blockChainData();
return bcdata;
}
else
return null;
}
//var bcdata = block.blockChainData();
Client1.js
const io = require('socket.io-client');
const io3 = require('socket.io-client');
var request;
let socket = io.connect("http://localhost:3000");
console.log("Client Running....\n");
socket.once("server2client", (data)=>{
console.log("Data Received from Server: ",data);
request = data;
})
let socket2 = io3.connect("http://localhost:3002");
socket2.once('client22other', (data)=>{
console.log("Data Received from Client: ", data);
})
const http = require('http').createServer();
const io2 = require('socket.io')(http);
const express = require('express');
const app = express();
io2.on('connection', (socket2)=>{
if(request == "Need Approval")
socket2.emit('client12other', "Client-1: Approved");
//console.log("Client-1 Approved Request to Add chain");
})
socket.on("sendblock", (obj)=>{
console.log("BlockChain Received from Server: ");
console.log( obj);
})
http.listen(3001,()=>{
console.log("Client 1 is listening at 3001!");
})
Client2.js
const express = require('express');
const app = express();
//const http = require('http').createServer();
var requ;
const cio = require('socket.io-client');
let socket = cio.connect('http://localhost:3000');
socket.on('server2client',(data)=>{
console.log("Received from server: ", data);
requ = data;
})
const cio2 = require('socket.io-client');
let socket2 = cio2.connect('http://localhost:3001');
socket2.on('client12other',(data)=>{
console.log("Received from client: ", data);
})
const http = require('http').createServer();
const sio = require('socket.io')(http);
const port = 3002;
sio.on('connection', (socket2)=>{
if(requ == "Need Approval")
socket2.emit('client22other', "Client-2: Approved");
})
socket.on("sendblock", (obj)=>{
console.log("BlockChain Received from Server: ");
console.log( obj);
})
http.listen(port, ()=>{
console.log("Client 2 is up! ");
})
These are the codes for my solution.
Are you making a new variable for each user connected to your socket?
like (io2 , io3)?

how to integrate dialogflow result to linebot (Node.js)?

I am creating the chatbot(Line) integrate the Google Dialogflow using node.js.
I can create the line chatbot from user input the text and echo some text, only.
And I can create the code from user input send command to Google Dialogflow, and dialogflow using
the NLU tech response text to the user.
But I need user input the text send to the dialogflow and response the text(A) , then send the text(A)(after code add some template button's code) to Line bot create show some template button to user.
How can I integrate two part code achieve user input text and through dialogflow result , using the result send to the line bot server?
user input -> dialogflow ->mycode(add some template button call line) ->linbot ->bot show template button to user
Thank you.
//----------------------------------
My dialogflow code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(
bodyParser.urlencoded({
extended: true
})
)
app.use(
bodyParser.json()
)
app.post("/webhook", function(req,res){
console.log(JSON.stringify(req.body, null, 2))
var intent = req.body.queryResult.intent.displayName;
var entityCity = req.body.queryResult.parameters["geo-city"];
if(intent === 'myIntent')
{
// here I need call bot.on method, but I don't known how to do.
// return res.json({
fulfillmentText: `I known your mean.`
});
}
else
{
return res.json({
fulfillmentText: `i am not sure your mean`
});
}
})
app.listen(process.env.PORT || 5566, function(){
console.log('server start ...');
})
//----------------------------------
My Line chatbot code:
var linebot = require('linebot');
var express = require('express');
var app = express();
const bot = linebot({
channelId: 'mychannelId',
channelSecret: 'mychannelSecret',
channelAccessToken: 'mychannelAccessToken'
});
bot.on('message',function(event) {
console.log('bot');
console.log(event);
var msg = event.message.text;
// here can add some template button code and reply to user.
});
const linebotParser = bot.parser();
app.post('/webhook', linebotParser);
var server = app.listen(process.env.PORT || 8080, function() {
var port = server.address().port;
});
//--------------------
My Line chatbot code other version:
const line = require('#line/bot-sdk');
const express = require('express');
const lineConfig = {
channelAccessToken: process.env.HEROKU_LINE_CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.HEROKU_LINE_CHANNEL_SECRET
};
const client = new line.Client(lineConfig);
const app = express();
app.post('/webhook', line.middleware(lineConfig), function(req, res) {
Promise
.all(req.body.events.map(handleEvent))
.then(function(result) {
res.json(result);
});
});
function handleEvent(event) {
switch (event.type) {
case 'join':
case 'follow':
return client.replyMessage(event.replyToken, {
type: 'text',
text: 'hello~'
});
case 'message':
switch (event.message.type) {
case 'text':
return client.replyMessage(event.replyToken, {
type: 'text',
text: (event.message.text+'~yu')
});
}
}
}
app.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
const line = require('#line/bot-sdk');
const express = require('express');
const dialogflow = require('dialogflow');
const uuid = require('uuid');
const lineConfig = {
channelAccessToken: process.env.HEROKU_LINE_CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.HEROKU_LINE_CHANNEL_SECRET
};
const client = new line.Client(lineConfig);
const app = express();
app.post('/webhook', line.middleware(lineConfig), function(req, res) {
Promise
.all(req.body.events.map(handleEvent))
.then(function(result) {
res.json(result);
});
});
async function handleEvent(event) {
switch (event.type) {
case 'join':
case 'follow':
return client.replyMessage(event.replyToken, {
type: 'text',
text: 'hello~'
});
case 'message':
switch (event.message.type) {
case 'text':
const response = await queryDF(event.message.text)
// you will get response from DF here
return client.replyMessage(event.replyToken, {
type: 'text',
text: (event.message.text+'~yu')
});
}
}
}
async function queryDF(message, projectId = 'your-project-id') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: message,
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
return responses[0].queryResult;
}
app.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
You need to user dialogflow npm detect Intent method

Update user balance in realtime in the browser from private ethereum blockchain

I would like to have a website that updates live the user's wealth from a private Ethereum blockchain.
Current Solution (broken)
I opened a websocket to a private Ethereum blockchain that is mining, I would like to update my Coinbase balance on the front end. My code is as follow:
const express = require("express");
const Web3 = require("web3");
var app = express();
app.get("/", (req, res) => res.send("hello world from ping ether application"));
app.get("/ping-ether", function(req, res){
var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
var event_newBlockHeaders = web3.eth.subscribe("newBlockHeaders", function(err, result){
if (err){
console.log(err)
} else {
let acctPromise = web3.eth.getAccounts().then(function(accts){
let balance = web3.eth.getBalance(accts[0]).then(function(bal){
console.log("user: ", accts[0]);
console.log("balance: ", bal);
res.end("new balance for user: " + bal)
});
});
}
});
});
// run the server
app.listen(3000, () => console.log("web app listening on port 3000"));
Clearly this is not updating live in the frontend even though the inner most callback is firing constantly as I can confirm on the console. I would like three things:
How should I change this code so that the front end has a live ticker of the coinbase balance
The code in general just smells bad with its nested promises. How can I refactor it so that I do not have to establish a websocket connection each time I navigate to /ping-ether?
Untested, but something like this should work:
const express = require("express");
const Web3 = require("web3");
var app = express();
var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
var balance = -1;
web3.eth.getAccounts().then(accounts => {
return web3.eth.subscribe("newBlockHeaders", (err, result) => {
if (err) {
console.log(err);
} else {
web3.eth.getBalance(accounts[0]).then(bal => {
console.log("user: ", accounts[0]);
console.log("balance: ", bal);
balance = bal;
});
}
})
}).then(() => {
app.listen(3000, () => console.log("web app listening on port 3000"));
});
app.get("/", (req, res) => res.send("hello world from ping ether application"));
app.get("/ping-ether", function (req, res) {
res.end("new balance for user: " + balance);
});
The main idea is to set up the websocket connection and subscription once, and then just respond to incoming web requests with the current balance. I also tried to clean up the nested promises by returning the subscription promise.
Update: I ended up using websocket, here's the solution:
import * as Web3 from 'web3' ;
import * as express from 'express' ;
import * as socketIO from 'socket.io';
import * as http from 'http' ;
const CLIENT_PATH = 'path/to/directory'
var app = express();
var server = http.Server(app);
var io = socketIO(server);
var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
app.get('/', (req,res) => {
res.sendFile(CLIENT_PATH + '/index.html');
});
web3.eth.getAccounts().then(accounts => {
display_account(accounts)
})
function display_account(accounts){
var user_0 = accounts[0]
web3.eth.subscribe('newBlockHeaders', (err, ret) => {
if (err){
console.log("error: ", err)
} else {
web3.eth.getBalance(user_0).then(bal => {
var msg = 'Balance for user ' + user_0 + ' is ' + bal
io.emit('message-1', msg)
console.log('emitted message: ', msg)
})
}
})
}
// use this instead of app.listen
server.listen(3000, () => {
console.log('listening on 3000')
});
And this is index.html.
<html>
<head></head>
<body>
<div id="message"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message-1', function(msg){
console.log(msg);
document.getElementById("message").innerHTML = msg;
});
</script>
</body>
</html>

TypeError: this.io is undefined socket.io.js:639

I try to connect from JavaScript to nodejs socket-server (for using webrtc in phonegap - PhoneRTC plugin)
I have server.js code:
var app = require('express')();
var server = require('http').createServer(app);
var webRTC = require('webrtc.io').listen(server);
var io = require('socket.io')(server);
var port = process.env.PORT || 1234;
server.listen(port);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/style.css', function(req, res) {
res.sendfile(__dirname + '/style.css');
});
app.get('/fullscrean.png', function(req, res) {
res.sendfile(__dirname + '/fullscrean.png');
});
app.get('/script.js', function(req, res) {
res.sendfile(__dirname + '/script.js');
});
app.get('/webrtc.io.js', function(req, res) {
res.sendfile(__dirname + '/webrtc.io.js');
});
webRTC.rtc.on('chat_msg', function(data, socket) {
var roomList = webRTC.rtc.rooms[data.room] || [];
for (var i = 0; i < roomList.length; i++) {
var socketId = roomList[i];
if (socketId !== socket.id) {
var soc = webRTC.rtc.getSocket(socketId);
if (soc) {
soc.send(JSON.stringify({
"eventName": "receive_chat_msg",
"data": {
"messages": data.messages,
"color": data.color
}
}), function(error) {
if (error) {
console.log(error);
}
});
}
}
}
});
start it: node server.js
then i have client side code:
<script src="http://my-saite:1234/socket.io/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = new io.Socket();
socket.connect('http://my-saite:1234');
// Add a connect listener
socket.on('connect',function() {
alert ('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
alert ('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
alert ('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};
</script>
and when i open it in web-browser i get error: TypeError: this.io is undefined socket.io.js:639
http://my-saite.com:1234 and http://my-saite.com:1234/socket.io/socket.io.js load fine,
639 line in socket.io.js is
/**
* `Socket` constructor.
*
* #api public
*/
function Socket(io, nsp){
this.io = io;
this.nsp = nsp;
this.json = this; // compat
this.ids = 0;
this.acks = {};
/*639 line --->*/ if (this.io.autoConnect) this.open();
this.receiveBuffer = [];
this.sendBuffer = [];
this.connected = false;
this.disconnected = true;
this.subEvents();
}
If someone has faced a similar problem - help. I would be grateful for your advice!
Using version 1.1.0 I guess?
Change the creation of a Socket object
var socket = io.connect('http://my-saite:1234');
Then the rest shouldn't be a problem
// Add a connect listener
socket.on('connect',function() {
alert ('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
alert ('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
alert ('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};

client server communication using node.js

In my client machine i have the following code
client.js
var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var exec = require('child_process').exec;
var server = http.createServer(function(req, res) {
switch(req.url) {
case '/vm/list':
getVms(function(vmData) {
res.end(JSON.stringify(vmData));
});
break;
case '/vm/start':
req.on('data', function(data) {
console.log(data.toString())
exec('CALL Hello.exe', function(err, data) {
console.log(err)
console.log(data.toString())
res.end('');
});
});
break;
}
});
server.listen(9090);
console.log("Server running on the port 9090");
in my server side machine am using following helper.js
var options = {
host: '172.16.2.51',
port: 9090,
path: '/vm/start',
method: 'POST'
};
var req = http.request(options, function(res) {
res.on('data', function(d) {
console.log(d.toString());
});
});
req.on('error', function(e) {
console.error(e);
});
req.end('');
while running node helper.js am getting { [Error: socket hang up] code: 'ECONNRESET' }
it doesn’t print data.tostring() contained in the client side.
Try adding res.writeHead(200); before your switch statement.
This method must only be called once on a message and it must be called before response.end() is called.
From http://nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers.
Update
After our discussion the following client.js works:
var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var exec = require('child_process').exec;
var server = http.createServer(function(req, res) {
switch(req.url) {
res.writeHead(200);
case '/vm/list':
getVms(function(vmData) {
res.end(JSON.stringify(vmData));
});
break;
case '/vm/start':
req.on('data', function(data) {
console.log(data.toString())
exec('CALL Hello.exe', function(err, data) {
console.log(err)
console.log(data.toString())
});
});
req.on('end', function() {
res.end('');
});
break;
}
});
server.listen(9090);
console.log("Server running on the port 9090");

Categories