my project is normal in web browser, HTML5 version is work.
But after compile to apk by command 'cocos run -p android', socket.io is useless server side cannot receive any information.
I know something is improper, but I cannot find a concrete solution. Please help me.THANKS
server.js as follow:
var io = require('socket.io').listen(3000);
console.log('Server on port 3000.');
var player = new Array();
var player_data = {
name: "",
kill: 0,
dead: 0
}
io.sockets.on('connection', function (socket){
console.log("come in");
socket.on('join_success', function (name){
console.log("name is"+name);
player_data.name=name;
player.push(player_data);
io.sockets.emit("updateAllPlayerData", player);
});
});
app.js as follow
var basicLayer = cc.Layer.extend({
ctor: function(){
this._super();
var size = cc.director.getWinSize();
var ball = new cc.Sprite(res.png1);
ball.x = 100;
ball.y = 100;
var ui = new GameUI;
sio_client= SocketIO.connect("http://localhost:3000");
sio_client.on("updateAllPlayerData", function(data){
alert(data);
playerNum = data.length;
for(var i=0; i<data.length; i++){
playerName.push(data[i].name);
killNum.push(data[i].kill);
deadNum.push(data[i].dead);
}
ui.updateInfo();
});
sio_client.on("connect",function(){
console.log("connect_success ");
var name=prompt("input your name","");
while(name==null || name==""){
name=prompt("input your name","");
}
sio_client.emit("join_success", name);
});
this.addChild(ball, 10, 100);
this.addChild(ui,2);
return true;
}
});
Related
I'm creating an Hybrid app in which I want to upload video to
server. Sometimes it uploads the video to the server but most of the
time Plugin shows the uploading progress to 99% and then it gives
null in success callback.
Thanks in advance. :-)
/********* OPENING CAMERA TO CPTURE VIDEO ***********/
function make_Video()
{
// capture callback
var captureSuccess = function(mediaFiles) {
var i, len , video_path;
if(mediaFiles.length > 0)
{
for (i = 0, len = mediaFiles.length; i < len; i += 1)
{
video_path = mediaFiles[i].fullPath;
Upload_Video(video_path);
}
}
};
// capture error callback
var captureError = function(error)
{
console.log('Error Code: ' + error.code);
};
navigator.device.capture.captureVideo(captureSuccess, captureError, { quality: 100,destinationType: Camera.DestinationType.FILE_URI });
}
/****************STORING VIDEO ON SERVER******************/
function Upload_Video(video_path)
{
var server = server_link; // MY SERVER LINK
var params = {'user_id':logged_in_user_id,'action':'update_intro_video'};
if (server)
{
// Specify transfer options
$('#modal_first_line').text(0+" %"+" Uploaded");
$('#new_modal').show();
var options = new FileUploadOptions();
options.fileKey = "user_video";
options.fileName = video_path.substr(video_path.lastIndexOf('/')+1);
options.mimeType = "video/mp4";
options.chunkedMode = false;
options.httpMethod = "POST";
options.params = params;
// Transfer picture to server
var ft = new FileTransfer();
//progree bar
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable){ var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100); $('#modal_first_line').text(perc+" %"+"
Uploaded"); } else {$('#new_modal').hide();
console.log("sorry! Upload Failed..."); } };
ft.upload(video_path, encodeURI(server) , function(data) {
$('#new_modal').hide();
console.log("SERVER RESPONSE: " + JSON.stringify(data));
},
function(error)
{
$('#new_modal').hide();
console.log("sorry! Upload Failed...");
}, options);
}
else{
$('#new_modal').hide();
console.log("sorry! Can't Upload File.");;
}
}
Solved.
The Problem was at server end. Configuration was making
trouble. post_max_size was set to 8Mb, so when limit of video
exceeds to 8MB, server was not allowing to save the video. I
increased the post_max_size to 100MB. To Increase the post_max_size
, I did the following steps
1. I Created a file .user.ini in the root directory
2. I placed the following code inside this file
file_uploads = O post_max_size = 100M upload_max_filesize
= 200M
Hope it will help someone.
I cannot make work AnalayserNode with AudioContext.createMediaElementSource in mobile devices. It does not work in Safari on iOS and does not work in Chrome on Android. When I do analayser.getByteFrequencyData(buffer); I always get an array with zeros. Is this a bug? where should I report it? Any workaround?
Full code below or in Codepen: http://codepen.io/elranu/pen/WQOerB
var initialized = false;
var audio = new Audio();
audio.src = "http://blogtalk.vo.llnwd.net/o23/show/6/884/show_6884921_2014_09_08_16_11_36.mp3";
audio.crossOrigin = "anonymous";
audio.preload = false;
function init(){
var context = new AudioContext();
var source = context.createMediaElementSource(audio);
var anal = context.createAnalyser();
anal.fftSize = 1024;
var buffer = new Uint8Array(anal.frequencyBinCount);
var lines = [];
var eq = document.getElementById('eq');
for(var index = 0; index < buffer.length; index++){
var line = document.createElement('div');
line.className = 'line';
lines.push(line);
eq.appendChild(line);
}
source.connect(anal);
anal.connect(context.destination);
setInterval(function(){
anal.getByteFrequencyData(buffer);
for(var index = 0; index < buffer.length; index++){
lines[index].style.height = buffer[index] + 'px';
}
}, 50);
}
function startAudio(){
if(!initialized){
init();
initialized = true;
}
audio.play();
}
function stopAudio(){
audio.pause();
}
.line {
width: 2px;
background-color: blue;
margin-left:3px;
display:inline-block;
}
#eq {
height: 500px;
}
<button onclick="startAudio()">Start Audio</button>
<button onclick="stopAudio()">Stop Audio</button>
<div id="eq">
</div>
Update: I have noticed that the AnalayserNode works on mobile if the source of the AudioContext is createBufferSource(). But this is not a viable way to solve the problem. Because to create a buffer I have to do the following request:
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function(){//stufff...};
And if I do this request, the mobile device will download the full audio, just render the frequency of the audio. With big audios this is no viable solution in mobile, because the user could wait a lot just to start playing.
An example to test this: http://webaudioapi.com/samples/visualizer/
I found the answer, unfortunately is a bug. More information here:
https://code.google.com/p/chromium/issues/detail?id=419446
i have problem to sync local image folder to server, i using titanium. When i run my program using android emulator, it works well. But when i try to run it using actual device, the program can not find the image file.
Below is my code. Please help.
$.btnfiles.addEventListener('click',function(e)
{
var dirTest = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory);
var dirList = dirTest.getDirectoryListing();
Titanium.API.info('Start loop for files length:' + dirList.length);
for ( i = 0; i < dirList.length; ++i){
var f = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, dirList[i]);
var data_to_send = {
"file": f.read(), "name1":Titanium.Filesystem.applicationDataDirectory
};
xhr = Titanium.Network.createHTTPClient({
// function called when an error occurs, including a timeout
onerror : function(e) {
//Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
xhr.setRequestHeader("enctype", "multipart/form-data");
xhr.open("POST","upload.php");
xhr.send(data_to_send);
Titanium.API.info('Namef: ' + dirList[i]);
Titanium.API.info('Name: ' + i);
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,dirList[i]);
if (file.exists()) { file.deleteFile(); }
}
});
These days i am trying to run an existing code from Adobe's Technical Evangelist Andrew Trice. The concept is to connect a database.com DB to phone gap application. here is the tutorial with the source code :
http://wiki.developerforce.com/page/Building_PhoneGap_Mobile_Applications_Powered_by_Database.com
THE ISSUE :
AFTER SUCCESSFUL INSTALLATION OF THE Childbrowser there is a specific error in the code :
Uncaught type error: cannot read property "ChildBrowser" of undefined at file:///android_asset/www/js/salesforceWrapper.js:17
here is the full code : ( i put comment in the line with the error)
function SalesforceWrapper() {
/* AUTHENTICATION PARAMETERS */
this.loginUrl = 'https://login.salesforce.com/';
this.clientId = '3MVG99qusVZJwhsmjZIlEaUsFRnadOib8Kv_MPwooFMEi.XpChrZ5cVEcKU_7NR1zfQjjmdHI7wMARXnLlgku';
this.redirectUri = 'https://login.salesforce.com/services/oauth2/success';
/* CLASS VARIABLES */
this.cb = undefined; //ChildBrowser in PhoneGap
this.client = undefined; //forceTk client instance
this.init();
}
SalesforceWrapper.prototype.init = function() {
this.client = new forcetk.Client(this.clientId, this.loginUrl);
// line 17 with the error
this.cb = window.plugins.childBrowser;
}
SalesforceWrapper.prototype.login = function (successCallback) {
this.loginSuccess = successCallback;
var self = this;
self.cb.onLocationChange = function (loc) {
if (loc.search(self.redirectUri) >= 0) {
self.cb.close();
self.sessionCallback(unescape(loc));
}
};
self.cb.showWebPage(self.getAuthorizeUrl(self.loginUrl, self.clientId, self.redirectUri));
}
SalesforceWrapper.prototype.getAuthorizeUrl = function (loginUrl, clientId, redirectUri) {
return loginUrl + 'services/oauth2/authorize?display=touch' + '&response_type=token&client_id=' + escape(clientId) + '&redirect_uri=' + escape(redirectUri);
}
SalesforceWrapper.prototype.sessionCallback = function(loc) { var oauthResponse = {};
var fragment = loc.split("#")[1];
if (fragment) {
var nvps = fragment.split('&');
for (var nvp in nvps) {
var parts = nvps[nvp].split('=');
oauthResponse[parts[0]] = unescape(parts[1]);
}
}
if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') {
console.log("error");
} else {
this.client.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url);
if ( this.loginSuccess ) {
this.loginSuccess();
}
}
this.loginSuccess = undefined;
}
ADOBE'S PHONE GAP IS A DANGEROUS TOOL , BUT IT IS STILL SO TOUGH TO MANIPULATE.
THANK YOU APRIORI FOR YOUR POSSIBLE PROPOSALS . AT THIS POINT I DON'T EXPECT TO GET THE ANSWER. I KNOW THAT THERE IS A BIG DISTANCE...
well people the problem was caused because of the index.html in which the reference of the childbrowser.js was in different folder.
it was in :
<script type="text/javascript" src="js/libs/ChildBrowser.js"></script>
instead of :
<script type="text/javascript" src="js/ChildBrowser.js"></script>
SO PEOPLE BE CAREFULL!!!
NOW MY PROBLEM HAS TO DO WITH ANOTHER FUNCTION BUT I THINK THAT IT IS SOMETHING SIMILAR.
THANK YOU ALL!
PLEASE TRY TO ANSWER IF YOU KNOW SOMETHING.
How to pull to refresh?
In Titanium appcelerator I need to show a list of content in tableview. If I pull the view it needs to update. In iPhone I complete but in Android it won't work. Please any one help to solve this problem in Android.
My Android code:-
tableView.addEventListener('scroll',function(e)
{
var offset = e.contentOffset.y;
if (offset < -65.0 && !pulling && !reloading)
{
var t = Ti.UI.create2DMatrix();
t = t.rotate(-180);
pulling = true;
arrow.animate({transform:t,duration:180});
statusLabel.text = "Release to refresh...";
}
else if((offset > -65.0 && offset < 0 ) && pulling && !reloading)
{
pulling = false;
var t = Ti.UI.create2DMatrix();
arrow.animate({transform:t,duration:180});
statusLabel.text = "Pull down to refresh...";
}
});
tableView.addEventListener('dragEnd', function(e)
{
if(pulling && !reloading)
{
reloading = true;
pulling = false;
arrow.hide();
actInd.show();
statusLabel.text = "Reloading...";
tableView.setContentInsets({top:60},{animated:true});
tableView.scrollToTop(-60,true);
arrow.transform=Ti.UI.create2DMatrix();
beginReloading();
}
});
Titanium now supports pull to refresh for BOTH Android (> v6.2.0) and iOS (>3.2.0) with a Titanium.UI.TableView, Titanium.UI.ListView or Titanium.UI.ScrollView object.
See the docs:
https://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.ListView
https://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.RefreshControl
Sample code taken from the docs:
var win = Ti.UI.createWindow({
fullscreen:true
});
var counter = 0;
function genData() {
var data = [];
for (var i=1; i<=3; i++) {
data.push({properties:{title:'ROW '+(counter+i)}})
}
counter += 3;
return data;
}
var section = Ti.UI.createListSection();
section.setItems(genData());
var control = Ti.UI.createRefreshControl({
tintColor:'red'
})
var listView = Ti.UI.createListView({
sections:[section],
refreshControl:control
});
control.addEventListener('refreshstart',function(e){
Ti.API.info('refreshstart');
setTimeout(function(){
Ti.API.debug('Timeout');
section.appendItems(genData());
control.endRefreshing();
}, 2000);
})
win.add(listView);
win.open();
Is this just the IOS code form the Kitchen Sink example?
There are a couple of attempts at getting this working on Android, though I haven't confirmed that any of them work as expected. From what I understand, the problem is that you can't get the offset the same way in Android as in IOS.
A quick Google search turned up this link, which was referenced from the official Appcelerator forums.
https://gist.github.com/903895