Cannot send message to other end using PeerJs connection - javascript

What I am trying to achieve is building a WebRtc application to support data and video exchange using PeerJs. My component.ts looks something like this:
ngOnInit() {
this.peer = new Peer();
setTimeout(() => {
this.mypeerid = this.peer.id;
},3000);
this.peer.on('connection', function(conn) {
conn.on('data', function(data){
console.log(data);
});
});
}
connect(){
var conn = this.peer.connect(this.secondId.nativeElement.value);
console.log(conn);
conn.on('open', function(){
conn.send('Message from that id');
});
}
The component.html looks like:
<h1>My id - {{mypeerid}}</h1>
<input type="text" #secondId>
<button (click)="connect()">Connect</button>
I would mention along with this that I have added the statement declare var Peer: any in typings.d.ts
The code runs well but unfortunately, conn.send('Message from that id') doesn't send console.log message at the other end.

Related

Failed to send the message by testing the tutorial in angularjs-chat

I get this error
TypeError: self.rooms[setup.to].publish is not a function
when sending the message. I already have the keys in pubnub, what should I do to make it work? My Angular version is 1.6.6.
// Send Messages
$scope.send = function() {
Messages.send({
data: $scope.textbox
});
};
I dunno if you use a form but try this way :
<form name="form" novalidate="true" ng-submit="send()">
$scope.send = function () {
if ($scope.form.$valid) {
var data = $scope.textbox;
$scope.textbox = null;
$scope.messages.push(data);//of push or send depend did proto
}
}

data received from c# to localhost is not shown in localhost webpage - nodemon app crashed

I'm trying to pass data from c# using console application to webpage using socket.io in real time
here is my c# code:
static void Main(string[] args)
{
int i = 0;
while(true)
{
//String data = Console.ReadLine();
String data = i.ToString();
if(data.Equals("exit", StringComparison.OrdinalIgnoreCase)) break; //If the user types "exit" then quit the program
SendData("127.0.0.1", 41181, data); //Send data to that host address, on that port, with this 'data' to be sent
//Note the 41181 port is the same as the one we used in server.bind() in the Javascript file.
System.Threading.Thread.Sleep(50); //Sleep for 50ms
i++;
}
}
public static void SendData(string host, int destPort, string data)
{
IPAddress dest = Dns.GetHostAddresses(host)[0]; //Get the destination IP Address
IPEndPoint ePoint = new IPEndPoint(dest, destPort);
byte[] outBuffer = Encoding.ASCII.GetBytes(data); //Convert the data to a byte array
Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //Create a socket using the same protocols as in the Javascript file (Dgram and Udp)
mySocket.SendTo(outBuffer, ePoint); //Send the data to the socket
mySocket.Close(); //Socket use over, time to close it
}
this is app.js
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var mySocket = 0;
app.listen(3000); //Which port are we going to listen to?
function handler (req, res) {
fs.readFile(__dirname + '/index.html', //Load and display outputs to the index.html file
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
console.log('Webpage connected'); //Confirmation that the socket has connection to the webpage
mySocket = socket;
});
//UDP server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("Broadcasting Message: " + msg); //Display the message coming from the terminal to the command line for debugging
if (mySocket != 0) {
mySocket.emit('field', "" + msg);
mySocket.broadcast.emit('field', "" + msg); //Display the message from the terminal to the webpage
}
});
server.on("listening", function () {
var address = server.address(); //IPAddress of the server
console.log("UDP server listening to " + address.address + ":" + address.port);
});
server.bind(41181);
finally this is index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
</head>
<body>
<script>
var socket = io();
socket.on('field', function (data) {
$("#field").html(data);
});
</script>
Data from C#: <div id="field"></div>
</body>
</html>
I used this article to implement it, everything, seems work fine for example when I send data to console of node.js it display it but as soon as I run the page (localhost:3000) after several printing "webpage connected" it shows this error in my console:
nodemon app crashed - waiting for file changes
can someone give me a solution?
this my result picture
Error may occure on a different levels. I see that you are not listenning socket errors, both for server and io.
Both of them are based on EventEmiter approach, so both have error event to listen.
Try to listen all possible error places, this will give you additional infromation on why your app crashed.
server.on("error", err => console.error("server error occured", err));
io.on("error", err => console.error("io error occured", err));
Update
Replace in index.html script loading for socket.io with this.
<script src="/socket.io/socket.io.js"></script>.
Then, all re-connection issues should gone. I'm not pretty sure how it is working.

How to insert data in ground.db in meteor when offline

i have a fully working meteor application but now i want to make it offline so I installed ground:db and appcache here is my package file:
...
ground:db
appcache
ground:localstorage
then I changed my Collections to this:
Gebiete = new Mongo.Collection('gebiete');
Straßen = new Mongo.Collection('straßen');
Nummern = new Mongo.Collection('nummern');
Ground.Collection(Gebiete);
Ground.Collection(Straßen);
Ground.Collection(Nummern);
and now when the app is online i can insert data and then i disconnect the app and relaunch (cordova) and no data is lost.
But when im offline and i want to insert sth. it doesnt work ;(. I thaught i dont have to change my methods file but here is one method just to make sure if it is right:
Meteor.methods({
neuesGebiet(Besitzer, Gebietsname, Gebietsnummer, Ort, Erstellungsdatum) {
Gebiete.insert({
Besitzer: Besitzer,
Gebietsname: Gebietsname,
Gebietsnummer: Gebietsnummer,
Ort: Ort,
Erstellungsdatum: Erstellungsdatum
});
}
});
and on the client the message is called like this:
import { Meteor } from 'meteor/meteor'
Template.neuesGebietErstellen.onCreated(function () {
this.subscribe('gebiete');
});
Template.neuesGebietErstellen.events({
"submit .add-Gebiet": function (event) {
var Gebietsname = event.target.Gebietsname.value;
var Gebietsnummer = event.target.Gebietsnummer.value;
var Ort = event.target.Ort.value;
var Besitzer = Meteor.userId();
var Erstellungsdatum = new Date();
var Datum = Erstellungsdatum.toLocaleDateString();
Meteor.call('neuesGebiet', Besitzer, Gebietsname, Gebietsnummer, Ort, Datum)
FlowRouter.go('/');
return false;
}
});
Please help me to get the data inserted when offline because i want it to be 100% offline
Thank you ;)
It's been a while since I used Ground:db but here's what I think you are missing...
First, you probably only want grounded collections on Cordova, so
if(Meteor.isCordova) {
Ground.Collection(Gebiete);
Ground.Collection(Straßen);
Ground.Collection(Nummern);
}
Then you need to use Groundmethods to store your method calls. So after the definition of the method:
Meteor.methods({
'neuesGebiet': function(...) {
...
}
});
if( Meteor.isClient ) {
Ground.methodResume([
'neuesGebiet'
]);
}

How get info from WebSocket using php?

I want get last transaction from blockchain.info On this site has API Websocket. But i can use API Websocket only for JavaScript. I can get last transaction using this code
<script type="text/javascript">
var conn = new WebSocket('ws://ws.blockchain.info/inv');
conn.onopen = function () {
console.log('open');
conn.send('{"op":"unconfirmed_sub"}');
}
conn.onclose = function () {
console.log('close');
}
conn.onerror = function (error) {
console.log('websocket error: ' + error);
}
conn.onmessage = function (e) {
console.log(e);
}
</script>
But i need get info above using php and after save in mysql. How can I get it through php?
Thank you in advance!
I found a library that solves the problem it phpws
Thanks to all.

NodeJS app only returning the Socket.io welcome message

I have a tracking app built with Node that is accessed by other sites in our network. They will access the app thru the head of their html files like so:
<title>Test</title>
<meta name="generator" content="TextMate http://macromates.com/">
<script src="http://mynetwork.com:1337/tracker.js?pid=publisher1&ps=home"></script>
</head>
<body>
The tracker.js file uses socket.io to connect to app.js which stores some data in MongoDB. For some reason when start socket.io then load a page that references that Tracker.js scripts I get an error "Uncaught SyntaxError: Unexpected identifier" on line 1 which is actually the “Welcome to socket.io." message and not the javascript thats in the file.
Here is what Tracker.js looks like:
(function(document, onload){
var io = document.createElement('script');
io.src = "//cdn.socket.io/stable/socket.io.js";
io.setAttribute('async', 'true');
if ( typeof onload === 'function') {
io.onloadDone = false;
io.onload = function() {
io.onloadDone = true;
onload();
};
io.onreadystatechange = function() {
if ( "loaded" === io.readyState && !io.onloadDone ) {
io.onloadDone = true;
io.onload();
}
};
}
(document.getElementsByTagName('head') || document.getElementsByTagName('body'))[0].appendChild(io);
});
(document, function(){
var socket = io.connect('http://mynetwork.com:1337');
socket.emit('adTracker',
{ adServer: 'datalunk', adZone : 'top_home', referingURL : 'site.com' }
);
socket.on('entrance', function(){
console.log('Response is:' + data.message);
});
});
The app.js file looks like this:
var io = require('socket.io');
var tracker = io.listen(1337);
tracker.configure(function () {
tracker.set('authorization', function (handshakeData, callback) {
if (handshakeData.xdomain) {
callback('Cross-domain connections are not allowed');
} else {
callback(null, true);
}
});
});
tracker.sockets.on('connection', function (socket) {
socket.on('entrance', {message: 'connection has been made to app.js'});
socket.on('adTracker', function (data) {
var adRequestData = data;
var pass = ["bigbooks"];
var databaseUrl = "user:pass#linus.mongohq.com:10006/node-test";
var collections = ["mads"]
var db = require("mongojs").connect(databaseUrl, collections);
db.cmnads.insert({adRequest : adRequestData}, {$set: {password: pass}}, function(err, updated) {
if( err || !updated ) console.log("User not updated");
else console.log("User updated");
});
});
});
Can anyone tell me why I would be getting the socket.io welcome message & error on line 1 and how do I resolve it?
(function(document, onload){
var io = document.createElement('script');
// rest of code
});
(document, function(){
// rest of code
});
});
should be
(function(document, onload){
var io = document.createElement('script');
// rest of code
})(document, function(){
// rest of code
});
});
You use an anonymous function that you should call (and you don't do it).
the correct syntax is (for a more simple example):
(function(a) {console.log(a)})('Hello World');
However you do:
(function(a) {console.log(a)});
('Hello World');
Make sure that the server has the latest stable version of Node installed. According to the official web site, it is currently v0.8.16.
Also, if socket.io server is running on http://mynetwork.com:1337/ then I believe you should be able to include the socket.io.js from http://mynetwork.com:1337/socket.io/socket.io.js
The fastest way to check if maybe the Node version is the source of problem is to install Node Version Manager, then v0.8.16 and finally run the socket.io server again
wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh
nvm install v0.8.16
nvm use 0.8.16
node yourSocketIOserver.js

Categories

Resources