I need continuous data receiving. but i tried with out setinterval() but no success. Then i tried setinterval() also no success i am receiving first response after sending message no success can you please help me.
this is the output;[enter image description here][1]
var HOST = '202.71.103.XXX';
var PORT = XXXX;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('init');
setInterval(getData, 1000);
});
function getData() {
console.log('fun called')
client.on('data', function(data) {
console.log('Get Data: ' + data)
Cdata = JSON.parse(data.slice(0, -2))
if (Cdata.ServerDist == 1) {
var sentMsg = '{"ClientID":"' + Cdata.ClientID + '","TrackSystemNos":"13992881XXX|"}';
client.write(sentMsg)
console.log('Sent Msg: ' + sentMsg)
}
});
}
[1]: https://i.stack.imgur.com/7Mt0Y.png
Okay so I am not 100% sure what your specific issue is but I wrote a simple client and server based on your code and it works pretty well so see if that helps you.
Server:
const net = require('net');
var dummy = {
ServerDist: 1
};
var server = net.createServer(function(socket) {
let temp = JSON.stringify(dummy)
console.log(temp);
socket.write(temp);
socket.on('data', data => {
let temp = JSON.stringify(dummy);
console.log(temp);
socket.write(temp);
});
});
server.listen(1337, '127.0.0.1');
Client
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 1337;
var client = new net.Socket();
client.connect(PORT, HOST, function () {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('init');
});
client.on('data', function (data) {
console.log('Get Data: ' + data);
let Cdata = JSON.parse(data);
if (Cdata.ServerDist === 1) {
let sentMsg = {ClientID: 'Bob', TrackSystemNos: '13992881XXX'};
client.write(JSON.stringify(sentMsg));
console.log('Sent Msg: ' + JSON.stringify(sentMsg))
}
}
);
Output:
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Old Answer
I believe your problem is setinterval is a asynchronous call. So as soon as you call it the code continues out of the connect function (most likely ending the connection). The setinterval gets the first response because it is there from the call before the close but since the connection is closed it doesn't get any more.
Have you tried using a while loop inside the connect to keep the connection open?
Related
I am trying to use protractor to call an api - it will return some JSON to me and I want to assert against it. I thought I had this working, until I tried to take it further and realised I hadn't got it right, but having a bit of a time trying to work out why.
I have placed some console.logs in and expected the sequence to be 1,2,3 however it appears to be 3 (test finished) then 2 and 1. So I suspect a promise issue.
code below:
'use strict';
var request = require('request');
var path = require('path');
var info;
//var fname = null;
var fname = 'joe';
describe("Sample test", function() {
var request = require('request');
var options = {
method: 'GET',
url: 'URL here',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: '{ "pay_load": [] }'
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
info = JSON.parse(body);
console.log('in the callback now');
//console.log('body :' + body);
//var count = Object.keys(info).length;
//console.log('body len:' + count);
//console.log('info :' + info);
fname = info.firstname;
console.log('firstname1 : ' + info.firstname);
console.log('firstname2 : ' + fname);
} else {
console.log('there was some error');
}
}
it("proves the API is alive - firstname is null", function() {
request(options, callback);
//expect(fname).toBe(null);
console.log('firstname3 : ' + fname);
//expect(fname).toBe(null);
//var common = new Common();
//common.checkForAPI();
});
So in my head I thought I would see "in the callback", then "firstname1", "firstname2" and finally "firstname3"
No, firstname3 will always get printed first, the way you have it. The reason for it as that all http requests in nodejs are async, so while your request is processing (or in flight), firstname3 will be printed. Then console.logs in your request callback.
Edit1 - Addressing the comment
Simple example which would print firstname1,2,3 in sequence (tested)
var request = function(cb) {
//basically call your request stuff and then when you are done call cb
console.log('firstname 1');
console.log('firstname 2');
cb();
};
request(function() {
console.log('firstname 3');
});
This prints
firstname 1
firstname 2
firstname 3
Or you can use a third party library called async and use async.tryEach to run tasks in series.
async.tryEach([
function getDataFromFirstWebsite(callback) {
// Try getting the data from the first website
callback(err, data);
},
function getDataFromSecondWebsite(callback) {
// First website failed,
// Try getting the data from the backup website
callback(err, data);
}
],
// optional callback
function(err, results) {
Now do something with the data.
});
Hello I'm trying to use PeerJS to send and receive message datas, so take a look to my code:
var peer = new Peer({key: 'my-personnal-peer-id-key'});
peer.on('open', function(id) {
console.log('My peer ID is: ' + id);
});
var dest = prompt("id de destination à appeller")
var conn = peer.connect(dest);
conn.send('Hello!');
conn.on('open', function() {
console.log('2')
// Receive messages
conn.on('data', function(data) {
console.log('3')
console.log('Received: ' + data);
});
});
In the window.prompt, I paste the destination peer id, but I don't receive any message in the console log at the following line:
console.log('Received: ' + data);
Please help me.
The connection has to have an event listener for 'data' to handle the received data. From your code, it looks like conn.send() is called before conn.on('data') is executed.
This means when conn.send is executed, the connection has no data event listener and hence the sent data is not handled at all.
It could be done like this
var conn = peer.connect(dest);
conn.on('open', function() {
console.log('2')
// Receive messages
conn.on('data', function(data) {
console.log('3')
console.log('Received: ' + data);
});
conn.send('Hello!');
});
I created a socket server using websocket module with this configuration taken from this example (with some changes):
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
I create my own client in html :
<html>
<head>
<script src='./js/jquery1-11-3-min.js'></script>
<script>
$(document).ready(function (){
buildwebsocket();
});
var ws;
function buildwebsocket(){
ws = new WebSocket("ws://192.168.0.96:5050",'echo-protocol');
ws.onopen = function(evt) { onOpen(evt) };
ws.onclose = function(evt) { onClose(evt) };
ws.onmessage = function(evt) { onMessage(evt) };
ws.onerror = function(evt) { onError(evt) };
}
function onOpen(ev){
//alert("konek men! mantap! :D");
$("#recmsg").append("connected!<br>");
}
function onClose(ev){
$("#recmsg").append("connection closed!<br>");
}
function onMessage(ev){
//alert("ada pesan datang!");
$("#recmsg").append(ev.data+"<br>");
}
function onError(ev){
$("#recmsg").append("connecting error!<br>");
}
function doSend(){
//writeToScreen("SENT: " + message);
var message = $("#pesan").val();
ws.send(message);
} function doClose(){
ws.close();
}
//function writeToScreen(message){
//var pre = document.createElement("p");
//pre.style.wordWrap = "break-word";
//pre.innerHTML = message;
//output.appendChild(pre);
//}
//window.addEventListener("load", init, false);
</script>
</head>
<body>
<button onclick='doClose()'>Close</button>
<textarea id='pesan'></textarea><br>
<button onclick='doSend()'>Kirim!</button>
<br>
received message
<div id='recmsg'>
</div>
</body>
</html>
The connection between client (first client) and the server was successfully established. I try to send messages from first client, then the server receives the message without any promblem, and then the message sent back to the first client, and the first client receives it. I can say the connection and the socket works well.
I try to establish another connection (second client), so I open the second client in another device. The connection is good. But, when I send messages from the first or the second client, the first client doesn't get the response but the second client gets it.
And if open the third client and then send a message, the first and the second client don't get the response. Only the last connected client receives the response from server, and there's no client receives any error messages.
Is it the cons of the module? or the server configuration must be changed/added?
Can I establish multi-client-supported-socket-server using this module?
You're not storing the connections on the server side. You're just setting them up on the server to communicate directly back and forth to the server. If you want messages going to the server to be sent back out to everyone, you need to set up the .on('message', ...) function for each connection on the server to have that behavior. To do this, you'll need to store the connections as they are created. Try this:
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
//create an array to hold your connections
var connections = [];
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
//store the new connection in your array of connections
connections.push(connection);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
//send the received message to all of the
//connections in the connection array
for(var i = 0; i < connections.length; i++) {
connections[i].sendUTF(message.utf8Data);
}
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
I am currently playing around with NodeJS and I have created a GET request fine, no issues with that, as soon as I try and post something to a form, I get 'socket hung up' error.
Here is my code:
var http = require('http');
var mathResult = 123;
var options = {
host: 'directus.darkscience.net',
path: '/',
port: '6789',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-urlencoded'
}
};
var post_req = http.request(options, function(res){
console.log('HERE');
res.setEncoding('utf8');
res.on('data', function(chunk){
console.log('CHUNK');
var result = chunk.match(/correct/i);
if(result.length > 0){
console.log(result);
}
});
});
post_req.on('error', function(e){
console.log('Post Error : ' + e.message);
});
post_req.end('amount='+mathResult);
I have no idea what I'm doing wrong.
Could anyone please point me in the right direction?
Anyone here can give me a few pointers working with sockets in node.js?
can open a tcp connection say on 172.0.0.1 on port 8000 for example using net.createConnection(port, host)
var net = require('net'),
querystring = require('querystring'),
http = require('http'),
port = 8383,
host = 172.123.321.213,
path = /path/toService,
_post = '';
var server = http.createServer(function(req, res) {
if(req.method == 'POST') {
req.on('data', function(data) {
body+=data;
});
req.on('end', function() {
_post = querystring.parse(body);//parser post data
console.log(_post);
})
}
var socket = net.createConnection(port, host);
var socket = net.createConnection(port, host);
socket.on('error', function(error) {
send404(res, host, port);
})
socket.on('connect', function(connect) {
console.log('connection established');
res.writeHead(200, {'content-type' : 'text/html'});
res.write('<h3>200 OK:
Connection to host ' + host + ' established. Pid = ' + process.pid + '</h3>\n');
res.end();
var body = '';
socket._writeQueue.push(_post);
socket.write(_post);
console.log(socket);
socket.on('end', function() {
console.log('socket closing...')
})
})
socket.setKeepAlive(enable=true, 1000);
}).listen(8000);
send404 = function(res, host, port) {
res.writeHead(404, {'content-type': 'text/html'});
res.write('<h3>404 Can not establish connection to host: ' + host + ' on port: ' + port + '</h3>\n');
res.end();
}
But now I need to send my data to the path defined - if I add the path to host then try connection then connection will fail.
Any ideas?
Thanks in advance
Your "socket" object is just a plain TCP socket which is just a simple bidirectional communication channel. The HTTP methods you're trying to use (e.g. res.writeHead()) don't pertain, so you'll have to write the request manually. Try something like this:
var socket = net.createConnection(port, host);
console.log('Socket created.');
socket.on('data', function(data) {
// Log the response from the HTTP server.
console.log('RESPONSE: ' + data);
}).on('connect', function() {
// Manually write an HTTP request.
socket.write("GET / HTTP/1.0\r\n\r\n");
}).on('end', function() {
console.log('DONE');
});