How get info from WebSocket using php? - javascript

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.

Related

Cannot send message to other end using PeerJs connection

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.

SignalR message from controller to view when event fires

I'm new to SignalR and trying to implement a notification when a particular event fires from an API .
What's tried:
Hub:
public class NotificationHub : Hub
{
private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
public static void Send( string content)
{
hubContext.Clients.All.addMessage(content);
}
}
Controller:
//static event from external API
public static void onTick(Tick TickData)
{
if(TickData.InstrumentToken == buy.InstrumentToken)
{
NotificationHub.Send(TickData.Bid);
}
}
What shall I use in the View to display the message which is triggered upon the condition?
View, tried :
$(document).ready(function () {
var conn = $.connection.NotificationHub;
conn.client.addMessage = function (message) {
alert(message);
};
});
Is there anything else needed to get this working?
Edit:
Ashley's answer got me closer and couple of things also was missing like below ,
connection.NotificationHubshould beconnection.notificationHub`
the order of the js files references should like
1 jquery-1.10.2.min.js
2 jquery.signalR-2.1.0.min.js
3 signalr/hubs
But now while executing it enters the .fail(function() and the console shows error ,
http://127.0.0.1:8080/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22notificationhub%22%7D%5D&_=1515664348026 Failed to load resource: net::ERR_CONNECTION_REFUSE
Please advise. Thanks in advance.
Make sure you include the SignalR hubs source:
<script type="text/javascript" src="~/signalr/hubs"></script>
You just haven't started the connection for SignalR, add this:
$.connection.hub.start().done(function() {
//connection has started :-)
}).fail(function() {
//connection has failed to start :-(
});
Using your example it would look like this:
$(document).ready(function () {
var conn = $.connection.NotificationHub;
conn.client.addMessage = function (message) {
alert(message);
};
$.connection.hub.start().done(function() {
//connection has started :-)
alert("connected");
}).fail(function() {
//connection has failed to start :-(
alert("failed");
});
});

Uncaught ReferenceError: web3 is not defined at window.onload

I'm trying to get my first dapp working; I know I'm close, but keep running into a problem with web3.
I am working on Windows 10, running a testrpc node via PowerShell. I used truffle to set up my folders & sample files, then compile and migrate.
I don't think I changed anything from the app.js file built by truffle... here is that code:
var accounts;
var account;
function setStatus(message) {
var status = document.getElementById("status");
status.innerHTML = message;
};
function refreshBalance() {
var meta = MetaCoin.deployed();
meta.getBalance.call(account, {from: account}).then(function(value) {
var balance_element = document.getElementById("balance");
balance_element.innerHTML = value.valueOf();
}).catch(function(e) {
console.log(e);
setStatus("Error getting balance; see log.");
});
};
function calcPremium() {
var premium = parseInt(document.getElementById("benefit").value)/10000;
document.getElementById("monthlyPremium").innerHTML = " Monthly Premium: $"+premium.toFixed(2);
};
function sendCoin() {
var meta = MetaCoin.deployed();
var amount = parseInt(document.getElementById("monthlyPremium").value);
var receiver = document.getElementById("receiver").value;
setStatus("Initiating transaction... (please wait)");
meta.sendCoin(receiver, amount, {from: account}).then(function() {
setStatus("Transaction complete!");
refreshBalance();
}).catch(function(e) {
console.log(e);
setStatus("Error sending coin; see log.");
});
};
window.onload = function() {
web3.eth.getAccounts(function(err, accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
refreshBalance();
});
}
I'm able to open the html file in a Chrome browser, with the MetaMask plugin enabled. However, it seems I'm unable to interact with the contracts in any way, due to the web3 error issue. The exact message is this post's subject line.
Thanks in advance for any help or guidance!
Could you please try it and see . I think the onload is giving the issue.
$(window).load function() {
web3.eth.getAccounts(function(err,accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
refreshBalance();
});
}

How to save incoming textfile from client from websocket connection

I'm trying to implement a websocket server in node.js without using any framework.
Sending messages from client to server is working fine. But now I tried to send a text file from client to server. I can see the content on the server side by using console.log in the terminal.
But:
how can i get the file information ? (name, created/edited date, etc. ?)
how can i save the file ?
Client code:
(function () {
'use strict';
var output, ws;
//Display logging information in the document
function log(s) {
var p = document.createElement("p");
p.style.wordWrap = "break-word";
p.textContent = s;
output.appendChild(p);
//Also log information on the javascript console
window.console.log(s);
}
//Send a message on the Websocket
function sendMessage(msg) {
console.log(ws.binaryType);
ws.send(msg);
console.log("Message sent");
}
//Initialize WebSocket connection and event handlers
function setup() {
output = document.getElementById("output");
ws = new window.WebSocket("ws://localhost:9999/");
//Listen for the connection open event then call the sendMessage function
ws.onopen = function () {
console.log("Connected");
document.getElementById('fl').onchange = function() {
sendMessage(document.querySelector('input[type="file"]').files[0]);
};
sendMessage("Hello Galileo!");
}
//Listen for the close connection event
ws.onclose = function (e) {
if(this.readyState == 2){
console.log('Connection is closing (Closing Handshake).')
}
else if(this.readyState == 3){
console.log('Connection closed. Has been closed or could not be opened.')
}
else{
console.log('Unhandled ReadyState: ',this.readyState);
}
console.log("Disconnected: " +
' reason:' + e.reason +
' was clean:' + e.wasClean +
' code:' + e.code);
}
//Listen for connection errors
ws.onerror = function (e) {
console.log("Error: " + e);
}
//Listen for new messages arriving at the client
ws.onmessage = function (e) {
console.log("Message received: " + e.data);
//Close the socket once one message has arrived
ws.close();
}
}
//Start running the example
setup();
})();
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Websocket Echo Client</title>
<meta charset="utf-8"/>
</head>
<body>
<h2>Websocket Echo Client</h2>
<div id="output"></div>
<input type="file" id="fl"/>
<script src="websocket.js"></script>
</body>
</html>
Server code
switch (opcode) {
case opcodes.TEXT:
this.payload = payload.toString("utf8");
winston.log('info','Text:\r\n', this.payload);
break;
case opcodes.BINARY:
console.log('info','File:\r\n', payload.toString("utf8"));
As far as I know the payload you're receiving on the server side does not contain the meta data about the file. I believe the File object is treated as a normal Blob with some extra meta data and the ws.send is only handling it like a Blob (it has no special handling for File).
The meta data can be accessed using
document.querySelector('input[type="file"]').files[0].name
document.querySelector('input[type="file"]').files[0].size
document.querySelector('input[type="file"]').files[0].type
And then send separately.

Code is giving error, "ReferenceError: CryptoJS is not defined" , while I have included required .js references, what's the reason?

Here is my code, I have included following .js files, onpage load it is giving error "ReferenceError: CryptoJS is not defined" why does it give that error when already js references are added. I am making a sharepoint-2013 app using office 365.
<script type="text/javascript" src="../Scripts/sha1.js"></script>
<script type="text/javascript" src="../Scripts/hmac-sha1.js"></script>
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
success: function (data) {
alert("IN Success");
alert(""+data.station_by_code);
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
include core-min.js before sha256.js
There are one of two forms for fixing this:
1: Manual Load, i have more success with this pattern:
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js", execOperation);
}
);
Example:
$.getScript("~hostUrl/_layouts/15/SP.RequestExecutor.js", getListDataREST);
2: Script on Demand:
SP.SOD.executeFunc('sp.userprofiles.js', 'SP.ClientContext', loadUserData);
This SharepointExchange posting, gives the usual JSOM implementation for most AppParts: Jquery is not firing on Page load SharePoint 2013
Error solved I added online references instead,
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha1.js"></script>
Maybe is too late, but:
var CryptoJS = require('crypto-js');
var hash = CryptoJS.HmacSHA256("Message", "secret");
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
console.log(hashInBase64); // qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
Works fine in node.js.

Categories

Resources