PeerJS error : Cannot receive messages - peerjs

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

Related

How can I connect WebSocket listening to one port to Net socket listening to another, using NodeJS?

This is the approach I tried but not working. I can forward the incoming messages from the WebSocket connection to the NetSocket, but only the first one received by NetSocket arrives to the client behind the WebSocket.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const NetSocket = require('net');
const net = new NetSocket.Socket();
// Web socket
wss.on('connection', function connection(ws) {
console.log((new Date()) + ' Remote connection accepted ' + ws.remoteAddress);
ws.on('message', function incoming(message) {
console.log('Received from remote: %s', message);
net.write(message)
});
ws.on('close', function(){
console.log((new Date()) + ' Remote connection closed');
});
});
// Net socket
net.connect(8745, '127.0.0.1', function() {
console.log((new Date()) + ' Local connection accepted');
});
net.on('data', function(data) {
console.log('Received from local: ' + data);
// Iterate the connected devices to send the broadcast
wss.clients.forEach(function each(c) {
if (c.readyState === WebSocket.OPEN) {
c.send(data);
}
});
});
net.on('close', function() {
console.log('Local connection closed');
});
After a new research I noticed that the problem was in my swift code.
private func setReceiveHandler() {
webSocketTask.receive { result in
defer { self.setReceiveHandler() } // I was missing this line
do {
let message = try result.get()
switch message {
case let .string(text):
print("Received text message: \(text)")
case let .data(data):
So, just adding defer { self.setReceiveHandler() } to my function, it started to work.
Note the defer statement at the start of the receive handler. It calls self.setReceiveHandler() to reset the receive handler on the socket connection to allow it to receive the next message. Currently, the receive handler you set on a socket connection is only called once, rather than every time a message is received. By using a defer statement, you make sure that self.setReceiveHandler is always called before exiting the scope of the receive handler, which makes sure that you always receive the next message from your socket connection.
I've got the information from:
https://www.donnywals.com/real-time-data-exchange-using-web-sockets-in-ios-13/

Node Js TCP Client not receiving data in a loop

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?

protractor promises - querying an API using "request"

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

Nodejs - websocket-node module: How to make multi-client socket-server works?

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

Getting the IP address of a socket inside a close event handler

socket.on('data', function(data)
{
console.log(socket.remoteAddress + ":" + socket.remotePort);
}
socket.on('close', function()
{
console.log(socket.remoteAddress + ":" + socket.remotePort);
}
The log from the data handler displays 127.0.0.1:8000.
The log from the close handler displays undefined:undefined.
I am trying to keep a list of connected sockets using IP:Port as the key. If I don't know which one closed, how can I remove it from the list? How can I get the IP:Port of the closed socket after it's closed?
This is how I'm keeping track of the clients:
server.on('connect', function(socket)
{
socket.key = socket.remoteAddress + ":" + socket.remotePort;
clients[socket.key] = socket;
socket.on('close', function()
{
delete clients[socket.key];
}
}
Much thanks to mscdex in the Node.js IRC channel for suggesting this solution!
socket.on('connect', function()
{
socket.address = socket.remoteAddress + ":" + socket.remotePort;//save the address in socket object
console.log(socket.remoteAddress + ":" + socket.remotePort);
});
socket.on('data', function(data)
{
console.log(socket.address );
});
socket.on('close', function()
{
console.log(socket.address );
});
just keep the data associate with the socket object.Hope this will help.
The remoteAddress property will be around even after disconnect once https://github.com/joyent/node/commit/8c38b07252d86f4eef91344f8df4f0c3e38bca35 is in a stable version of Node.js. io.js will have it in the next release: https://github.com/iojs/io.js/issues/1157