Socket programming in yii2 to provide web service support to the mobile app - sockets

I have a requirement to provide the real time data to the mobile app through web services. I have developed the project in yii2 and want to implement socket programming so that i could connect the mobile app and can send the updated real time data to the app.
For Details :
We have to provide the live tracking feature to our mobile app user.
For that we are storing the mobile app user's current location(Lat/long) and storing it on server. When any user want to track his friend(Which is the user of our app) location he can, for which we have to keep sending his friend's current location to the app so that he can see him moving on map when he is roaming anywhere.
I have google for the socket programming with Yii2 but every where i am getting the example for chat functionality through sockets.
Can any body help who has worked something matching with my requirements.
Socket programming to send data from server to mobile app client.
Thanks in advance.

Finally, After putting so much efforts and spent a week of time on R&D i just got what i was require.
Here i am posting the solution which i have developed for my requirements considering for those who have the similar requirements, may be it could help full for them :
Server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var clientsids = {};
var response_array = get_response_array();
server.listen(8786);
io.on('connection', async function (socket) {
var uchannel = socket.handshake['query']['r_var'];
var myid = socket.handshake['query']['myid'];
clientsids[uchannel+'_'+myid] = socket.id;
socket.join(uchannel);
socket.emit('connectSuccess',response_array);
//sending current data to the user
socket.on('currentlocation', function(data) {
console.log("User with id :"+data.myid+ " has shared the location : lat :"+data.lat+",lng :"+data.lng+" in channel :"+data.channel);
//dump user location to a file for future save to the db
fileobj.savelocation(data.myid,data.lat,data.lng);
response_array = get_response_array();
response_array['msg_code'] = 103;
response_array['msg'] = get_msg_code(103);
var datainfo = {};
datainfo['lat'] = data.lat;
datainfo['lng'] = data.lng;
datainfo['channel_name'] = data.channel;
datainfo['u_id'] = data.myid;
response_array['data'] = datainfo;
fileobj.dumpdata("User with id :"+data.myid+" has shared the location : lat :"+data.lat+",lng :"+data.lng+" in channel :"+data.channel+" \n"+JSON.stringify(response_array));
io.to(data.channel).emit(data.channel, response_array); //broadcast the data to all the users in the channel
//console.log('current clients :'+ JSON.parse(clientsids));
});
socket.on('disconnect', function() {
//redisClient.quit();
socket.disconnect('disconnect');
});
});
Client.php
var room ='';
var myid ='';
var socket ='';
$( document ).ready(function() {
room = $("#channel").val();
room2 = $("#channel2").val();
myid = $("#myid").val();
socket = io.connect('serverip:port',{
query: 'r_var='+room+'&myid='+myid
});
socket.on(room, function (data) {
$( "#notifications" ).prepend( "<p><strong>Message :" + data.msg + " </strong> <strong>Channel :" + data.data.channel_name + "</strong> <strong>Lat :" + data.data.lat + "</strong> <strong>Long :" + data.data.lng + "</strong></p>" );
});
socket.on('connectSuccess', function (data) {
$( "#notifications" ).prepend( "<p><strong>" +data.msg+ "</strong>: ");
});
});

Related

Microsoft Bot Framework channel integration: more endpoints?

I'm using Microsoft Bot Framework using the channel registration product and the REST API. I have setup the "messaging endpoint" and everything works fine for sending and receiving messages.
But I don't just want to send/receive messages. Something as simple as setting up a welcome message seems impossible because my endpoint receives nothing other than messaging events (when the bot is in the channel / conversation.)
Is there something I have missed?
I would like to setup several endpoints, or use the same, whatever, to listen to other types of events.
You need to implement in the MessageController something like these:
Pay attention in the else if. The funcition in the controller is HandleSystemMessage.
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
IConversationUpdateActivity update = message;
var cliente = new ConnectorClient(new System.Uri(message.ServiceUrl), new MicrosoftAppCredentials());
if (update.MembersAdded != null && update.MembersAdded.Count > 0)
{
foreach(var member in update.MembersAdded)
{
if(member.Id != message.Recipient.Id)
{
//var username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var username = message.From.Name;
var reply = message.CreateReply();
//string dir = System.AppDomain.CurrentDomain.BaseDirectory + "Images" + Path.DirectorySeparatorChar + "cajamar.png";
string dir = HttpRuntime.AppDomainAppPath + "Images" + Path.DirectorySeparatorChar + "cajamar.png";
reply.Attachments.Add(new Attachment(
contentUrl: dir,
contentType: "image/png",
name: "cajamar.png"
));
reply.Text = $"Bienvenido {username} al ChatBot de convenios:";
cliente.Conversations.ReplyToActivity(reply);
//var reply = message.CreateReply();
//reply.Text = $"El directorio base es: {HttpRuntime.AppDomainAppPath}";
//cliente.Conversations.ReplyToActivityAsync(reply);
}
}
}
}

Wrapper for Bloomberg Data License Web Services

I'm looking now in Bloomberg Data License Web Services. Note, that this is different from Bloomberg API ( Session/Service/Request, b-pipe, etc ). It is SOAP-based solution to retrieve reference data from Bloomberg DBs. I created a test application just to quickly evaluate this solution:
var client = new PerSecurityWSClient("PerSecurityWSPort");
client.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2("{path-to-certificate}", "{password}");
client.ClientCredentials.UserName.UserName = "";
client.ClientCredentials.UserName.Password = "";
client.ClientCredentials.Windows.ClientCredential.Domain = "";
var companyFields = new string[] { "ID_BB_COMPANY", "ID_BB_ULTIMATE_PARENT_CO_NAME" , /* ... all other fields I'm interested in */ };
var getCompanyRequest = new SubmitGetCompanyRequest {
headers = new GetCompanyHeaders { creditrisk = true },
instruments = new Instruments {
instrument = new Instrument[] {
new Instrument { id = "AAPL US", yellowkey = MarketSector.Equity, yellowkeySpecified = true },
new Instrument { id = "PRVT US", yellowkey = MarketSector.Equity, yellowkeySpecified = true }
}
},
fields = companyFields
};
var response = client.submitGetCompanyRequest(getCompanyRequest);
if(response.statusCode.code != SUCCESS) {
System.Console.Error.WriteLine("Response status is " + response.statusCode);
return;
}
var retrieve = new RetrieveGetCompanyRequest { responseId = response.responseId };
RetrieveGetCompanyResponse getCompanyResponse = null;
do {
System.Console.Write("*");
Thread.Sleep(1000);
getCompanyResponse = client.retrieveGetCompanyResponse(retrieve);
} while (getCompanyResponse.statusCode.code == DATA_NOT_AVAILABLE);
if (getCompanyResponse.statusCode.code != SUCCESS) {
System.Console.Error.WriteLine("Response status is " + response.statusCode);
return;
}
System.Console.WriteLine();
foreach (var instrumentData in getCompanyResponse.instrumentDatas) {
Console.WriteLine("Data for: " + instrumentData.instrument.id + " [" + instrumentData.instrument.yellowkey + "]");
int fieldIndex = 0;
foreach (var dataEntry in instrumentData.data) {
if (dataEntry.isArray) {
Console.WriteLine(companyFields[fieldIndex] + ":");
foreach(var arrayEntry in dataEntry.bulkarray) {
foreach(var arrayEntryData in arrayEntry.data) {
Console.WriteLine("\t" + arrayEntryData.value);
}
}
}
else {
Console.WriteLine(companyFields[fieldIndex] + ": " + dataEntry.value);
}
++fieldIndex;
}
System.Console.WriteLine("-- -- -- -- -- -- -- -- -- -- -- -- --");
}
The code looks somewhat bloated (well, it is indeed, SOAP-based in 2015). Hence is my question -- I assume there should be some wrappers, helpers, anything else to facilitate reference data retrieval, but even on SO there is only one question regarding BB DLWS. Is here anyone using DLWS? Are there any known libraries around BB DLWS? Is it supposed to be that slow?
Thanks.
I'm just getting into this myself. There are two options for requesting data: SFTP and Web Services. To my understanding, the SFTP option requires a Bloomberg application ("Request Builder") in order to retrieve data.
The second option (Web Services) doesn't seem well-documented, at least for those working with R (like myself). So, I doubt a library exists for Web Services at this point. Bloomberg provides an authentication certificate in order to gain access to their network, as well as their web services host and port information. Now, in terms of using this information to connect and download data, that is still beyond me.
If you or anyone else has been able to successfully connect and extract data using Bloomberg Web Services and R, please post the detailed code to this Blog!

hello, is there a way for consuming a Rest service in an app for windows 8.1 using WinJS?

hello I'm trying to consume a REST service in an app for windows 8.1, I'm so gratefull if you can give me more information related about this topic, thanks !!
You could use the XMLHttpRequest object. But, since you are using WinsJS, the WinJS.xhr function would be more convenient.
Here's an example on how to use it:
(function () {
"use strict";
var app = WinJS.Application;
app.onactivated = function (args) {
// Change RSS feed URL as you need to.
var resDiv = document.getElementById("divResult"),
rssURL = "http://blogs.windows.com/windows/b/appbuilder/rss.aspx";
// Call WinJS.xhr to retrieve an XML feed from the Web.
WinJS.xhr({
url: rssURL,
responseType: "document"
}).done(
// When the result has completed, check the status.
function completed(result) {
if (result.status === 200) {
// Get the XML document from the results.
var xmlDocument = result.responseXML,
title = xmlDocument.getElementsByTagName('title')[0];
// Update the HTML in the app.
resDiv.style.backgroundColor = "lightGreen";
resDiv.innerText = "Downloaded RSS feed from the " + title.textContent + " blog.";
}
});
};
app.start();
})();

Get remote endpoint properties on node.js socket close/end events

I have a node.js server which keeps track of all "clients" connected to it, using an associative array of sockets, because I need to send some data to specific clients sometimes. The keys in that array are strings composed of
socket.remoteAddress + ':' + socket.remotePort
and values are socket instances passed to the callback provided to net.createServer(...)
Sometimes the clients disconnect for one reason or another and I receive the 'end' and then 'close' events. I'd like to remove the disconnected clients from my client registry but in the close/end event callbacks, the remoteAddress and remotePort variables are undefined. Can they be retrieved somehow?
To illustrate:
var registry = {}
var server = net.createServer(function (socket) {
socket.on('connect', function(){
registry [socket.remoteAddress + ':' + socket.remotePort] = socket;
});
socket.on('close', function(had_error){
// ******************************************************
// socket.remoteAddress and remotePort are undefined here
// ******************************************************
var id = socket.remoteAddress + ':' + socket.remotePort;
// *************************************************************
if(registry.hasOwnProperty(id)
delete socket.id;
});
});
I think you should use socket.id instead of creating your own object property that might not be unique
socket.on('connect', function(){
registry [socket.id] = socket;
});
UPDATE
Node provides basic http API. Http is stateless. HTTP sessions allow associating information with individual visitors but node doesn't have a native sessions support.
Take a look at express, it is a nice web framework with sessions support
Also, if you need to send messages in a realtime fashion, take a look at socket.io
UPDATE V2
You can add your own ID property to the socket object:
function randomID(len){
//Generate a random String
return randID;
}
var registry = {}
var server = net.createServer(function (socket) {
socket.on('connect', function(){
var uid = randomID(32);
socket.id = uid;
registry [uid] = socket;
});
socket.on('close', function(had_error){
var uid = socket.id;
// *************************************************************
console.log("Socket ID " + uid + " disconnected")
});
});

How do I subscribe to Facebook Realtime API?

I'm developing a desktop application and I want to subscrbe to Facebook Realtime API.
This is my code on the client (WPF app):
After my code is executed, at fb.Post I get the following error: (OAuthException) (#15) This method is not supported for native apps.
I also tried the code from ASP.NET and got the same error, so I don't this the message is very intuitive.
How can I solve this problem and succesfully subscribe to Facebook Realtime API?
var tokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + Constants.Facebook.AppId + "&client_secret=" + Constants.Facebook.AppSecret + "&grant_type=client_credentials";
var requestToken = WebRequest.Create(tokenUrl);
HttpWebResponse res = (HttpWebResponse)requestToken.GetResponse();
Stream resst = res.GetResponseStream();
var sr = new StreamReader(resst);
string responseToken = sr.ReadToEnd();
var app_access_token = responseToken.Replace("access_token=", "");
var callback_url = "[MY CALLBACK URL]";
var fb = new FacebookClient(app_access_token);
var parameters = new Dictionary<string, string>();
parameters.Add("object", "user");
parameters.Add("fields", "feed");
parameters.Add("callback_url", callback_url);
parameters.Add("verify_token", "abc");
parameters.Add("access_token", app_access_token);
var uri = string.Format("https://graph.facebook.com/{0}/subscriptions?", Constants.Facebook.AppId);
var response = fb.Post(uri, parameters);
Your application configured as "Native Application" in developer app (advanced settings) and as stated in error this type of apps can't use Real-Time updates (sounds like a good reason to me).
Documentation for Real-Time Updates omit this info, you can file a bug and see what officials say...