hi
i experiencing websocket connections using php,nodejs for server side and using jquery for client side, soon i hope to publish my simple experiments for others newbies. for now i with this simple php script that i used to debug my apps it's a simple client that send data to nodejs http.server and stamp
the response received i hope that for someone it will be useful
Kevin Pham
the code:
<?
$host = 'localhost'; //where is the websocket server
$port = 9000;
$local = "http://localhost/"; //url where this script run
$data = 'hello world!'; //data to be send
$head = "GET / HTTP/1.1"."\r\n".
"Upgrade: WebSocket"."\r\n".
"Connection: Upgrade"."\r\n".
"Origin: $local"."\r\n".
"Host: $host"."\r\n".
"Content-Length: ".strlen($data)."\r\n"."\r\n";
////WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, "\x00$data\xff" ) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000); //receives the data included in the
websocket package "\x00DATA\xff"
$retdata = trim($wsdata,"\x00\xff"); //extracts data
////WebSocket handshake
fclose($sock);
echo $retdata //data result
?>
AndroidWorld - Diễn đàn Android Việt Nam, forum Android, nơi trao đổi thông tin kiến thức về lập trình Android, phần mềm Android, rom cook điện thoại Android, tin tức công nghệ
Thursday, June 28, 2012
php simple websocket client
Objective-C creating objects, methods and variables
In this tutorial we will be creating a console application to try every part of our code out. Please make sure that the console is not set to its default language, which is C and is instead set to foundation.
The first thing we need to do is create a no project with Xcode. I will be naming mine “test” but you really don’t need to follow along with that much detail since it is not needed at this stage with the level of coding we will be doing.
The next thing we will need to do is open up our “test.m” file through Xcode. This file contains the default main method but we are going to be creating objects and variables.
1 | #import <Foundation/Foundation.h> |
Now you are going to need to create an interface and an implementation of the class made in the interface. Luckily for us Xcode has an auto complete feature built in that look something like this.
Until we start modifying the information in the interface and implementation you can just leave it with its default values that are given when it auto completes.
1 | #import <Foundation/Foundation.h> |
The next thing we will be doing is creating the actual object from our interface. This requires us to create an object name, which in this case will be a “Person”, and it also requires a super class, which we will send to “NSObject.”
1 | @interface Person : NSObject |
Note: It is standard and common practice to associate objects as follows: “PersonObjectSomething.” You will notice that when naming all of the words are capitalized. This is common practice when naming classes. When naming methods it is standard to leave that first letter as a lower case like so “thisTestMethod.”
The next things that are required are instance variables. These are variables/information that is associated with the object. For example if we created an object that was a cup then we would have instance variables for weight, liquid capacity, circumference of base, etc.
For our person object we will be creating the instance variables for age and height. Normally I would like to do a name but I will be leaving the string library for another tutorial.
When declaring instance variables, or any variables, you will need to create the data type first then give the variable a name. A simple example of this would be an integer data type named x as you commonly see in math. You can also assign the variable a value when it is first declared.
1 | int x; |
Once we have declared our instance variables for person you should have something that looks like this.
1 | #import <Foundation/Foundation.h> |
Now that we have created our Person interface’ variables we will need to create methods. If you have never worked with methods you may know them by another name, which is a function. If you still haven’t worked with them then you should know that a method is essentially a small sub program running in a larger one. Methods naturally return a value as well however, you can change the method type to void and not have to worry about returning a value.
There are two kinds of basic methods used in programming languages. The first one is called an accessor method and the second one is called a mutator method. The accessor method simply accesses a variable from the object it is derived from and returns said variable. And the mutator changes the value of the variable in some way. For this program we will be using these two types along with another void type that will print information on the screen.
In order to create a method, we must first link to it in the interface section of the code so our object can use it with the variables it contains. For this program we will need to set the height and age, access the height and age, and print the information on the screen. Add this section of code to your interface.
1 | -(void)setHeight: (int) x; |
You should now have an interface that looks like this.
1 | #import <Foundation/Foundation.h> |
The next thing we will need to do is create the body of our object. We can do this by filling out the implementation section of our code. As you can see in your Xcode’ code view we have a place for the class to be written and a place for the methods. We are going to change the class to “Person” and start writing in our accessor and mutator methods. When done we will have the following code.
1 | @implementation Person |
Now that we have created our methods and instance variables we will go ahead and create this object and put it into memory. The following code is what we currently have for a main method.
1 | int main (int argc, const char * argv[]) { |
When creating objects there are two main terms you will need to familiarize yourself with. The first term is “init” Which of course stands for initialize. This is when you tell the machine that you are ready to use the object. The next term you should be familiar with is “alloc,” it is short for allocate. This is the process of freeing up memory in your ram for the storage of the object.
The code to initialize and allocate an object is written as follows.
1 | Person *p1; |
In this process we first named the object p1 and assigned it enough space to hold the object “Person” in memory. The next line of code simply initializes the object so it is ready for our use.
When you are done using your object and you would like to delete it you must include an object release.
1 | [p1 release]; |
In between creating the object in memory and removing it from memory we are going to add some code to set the variables, access the variables and display what the object holds on screen.
In order to display an object’s methods you will need to follow the form of writing the code as follows.
1 | [p1 setAge:18]; |
You can see that the object is placed within square brackets and the first statement is the object name itself. The second statement accepts the method that you would like to call on then a colon and some parameters if you made a method that accepts arguments.
When using a method that returns a value it is possible to load the data type returned into another variable as long as it is of the same data type. We use an example of this with the following lines. You can also use a variable as an argument when setting an objects variable.
1 | int g = [p1 getHeight]; |
The entire program looks as follows:
1 | #import <Foundation/Foundation.h> |
If you have any questions or concerns please feel free to comment below.
Monday, June 25, 2012
Eclipse Indigo for Android Development on Mac OS X Snow Leopard
I decided to install the latest version of Eclipse, Indigo, and configure it to do Android application development. My specific final target is to build the VLC Player for Android. Below are my notes for installing such an Eclipse configuration for Android development on a clean Mac OS X Snow Leopard system.
Install Android SDK
We will need the Android Native Development Kit (NDK) in order to compile the Android VLC JNI library:
In the recent versions of Eclipse, the default behavior for search is to reuse the editor. This default behavior can be annoying because it prevents you from being able to simultaneously view more than one search result. Opening a new search result would reuse the editor tab and cause the previous search result to become unavailable. To configure Eclipse to open each search result in a new editor tab, do the following:
Add the ADT to Eclipse:
Optionally, add the Javascript Development Tool (JDT):
If interested, see the next post about compiling the VLC Player for Android.
Install Android SDK
- Download latest Android SDK (I downloaded “android-sdk_r12-mac_x86.zip”).
- Unzip and move the extracted “android-sdk-mac_x86″ directory to “/Applications”, so you end up with “/Applications/android-sdk-mac_x86″.
- Add the following to the end of your bash environment configuration file “~/.profile”. (The tilde symbol ~ translates into your home directory “/Users/your_username”.) export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Home
export ANDROID_SDK=/Applications/android-sdk-mac_x86
export PATH=$PATH:$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools
export NO_NEON=1- Mac OS X Snow Leopard comes with the 64bit version of Java 1.6 installed by default. We are just setting the JAVA_HOME to point at it.
- The PATH is optional but will make it easy for you to run the Android SDK Manager by typing “android” or the Android Debug Bridge by typing “adb” in the Terminal.
- Set NO_NEON to prevent Android compilation from using the Neon CPU enhancements which are not supported on all Android devices (including the Emulator).
- Run the Android SDK Manager, by launching $ANDROID_SDK/tools/android, to install support for one or more Android OS platform versions. (It is mandatory that you install at least one OS platform version.)
- Click on “Installed packages” to see what is installed by default, usually just the Android SDK Tool and Platform-tools.
- Click on “Available packages”, expand “Android Repository”, and select the SDK Platform OS version that you want to develop for. For example, if you wish to do Honeycomb development (or your Android phone has Honeycomb), you can check “SDK Platform Android 3.0, API 11, revision 3″. You might wish to also get the samples by checking “Samples for SDK API 11, revision 1″.
- Click the “New…” button, name your emulator, select a platform OS version for the target, input a SD Card size like 32 or more, and hit the “Create AVD” button. The SD Card size is optional but some programs may fail to run if a SD Card is not present.
- Periodically, to update your installation, you may wish to go to “Installed packages” and click the “Update All…” button. This will return all updates (even for items not installed) which are applicable; you will need to select Reject for those items which you don’t want to install/update.
We will need the Android Native Development Kit (NDK) in order to compile the Android VLC JNI library:
- Download the latest Android NDK (I downloaded “android-ndk-r6-darwin-x86.tar.bz2″).
- Unzip and move the extracted “android-ndk-r6″ directory to “/Applications”, so you end up with “/Applications/android-ndk-r6″.
- Edit “~/.profile” to add the following: export ANDROID_NDK=/Applications/android-ndk-r5b
export PATH=$PATH:$ANDROID_NDK:$ANDROID_NDK/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin
- Download the latest Eclipse.
- Select “Mac OS X (Cocoa)” in the “Packages for” drop-down listbox at the top to filter for only Mac versions.
- Find the Eclipse flavor you want. If you aren’t sure, I recommend getting “Eclipse IDE for Java Developers”. Click on the “Mac OS X 64 Bit” to the right to download. (I downloaded “eclipse-java-indigo-macosx-cocoa-x86_64.tar.gz”.)
- Unzip and copy the extracted “eclipse” directory to “/Applications”, so you will end up with “/Applications/eclipse”.
- Start Eclipse and select your workspace location. (If you select an old location which was used by an older version of Eclipse, make sure to delete the “.metadata” sub-directory there first; otherwise, your new Eclipse will display old plug-ins and IDE modes which it may not have installed.)
In the recent versions of Eclipse, the default behavior for search is to reuse the editor. This default behavior can be annoying because it prevents you from being able to simultaneously view more than one search result. Opening a new search result would reuse the editor tab and cause the previous search result to become unavailable. To configure Eclipse to open each search result in a new editor tab, do the following:
- Go to menu “Eclipse->Preferences->General->Search”.
- Uncheck the “Reuse editors to show matches” option.
Add the ADT to Eclipse:
- Run Eclipse.
- Select Help->Install New Software…
- Input “https://dl-ssl.google.com/android/eclipse/” into the “Work with:” field. Hit Enter. The table below should populate automatically. (You can use the optional Add button if you want to bookmark this URL.)
- In the table, expand “Developer Tools” to see what it contains.
- Check the “Developer Tools” box to select all. (If you want just the minimum, check only “Android Development Tools”.)
- Click Next, Next, select “I accept the terms of the license agreements” radio button, and click Finish.
- If the Security Warning dialog about the “unsigned content” appears, click Ok to accept.
- Click on “Restart Now” to restart Eclipse.
- Under Eclipse, go to menu Eclipse->Preferences.
- Select Android.
- In the “SDK Location”, browse to your android install directory (directory pointed at by $ANDROID_SDK or “/Applications/android-sdk-mac_x86″).
- Hit Apply and you should see the Android platform versions you installed earlier populate the table.
- Hit Ok to close the dialog.
Optionally, add the Javascript Development Tool (JDT):
- Go to Eclipse menu Help->Install New Software…
- Click on the dropdown arrow for the “Work with:” box and select “Indigo – http://download.eclipse.org/releases/indigo”. (If you don’t see this entry, just type in the URL manually.) The table will populate with a bunch of Indigo-compatible plugins.
- Type “javascript” into the “type filter text” field to show only the Javascript related plugins.
- Check the “JavaScript Development Tools” (for example, under “Programming Languages”) and click Next, Next, accept the license, Finish.
- Click on “Restart Now” to restart Eclipse.
If interested, see the next post about compiling the VLC Player for Android.
Saturday, June 23, 2012
How to Send an SMS Progammatically
This post shows the basics for sending an SMS message from within an iPhone application. The class you’ll need to use is MFMessageComposeViewController which presents the standard SMS interface for composing and sending messages. As you’ll see in the example that follows, you can also pre-populate the body of the message as well one or more recipients for the SMS.
SMS View Controller Interface
The view controller that will send the SMS is shown below, notice the message composer import statement as well as the reference to the protocolMFMessageComposeViewControllerDelegate. The delegate has just one method where you can check the result of the message (sent, cancelled or failed) and this is also where you dismiss the view controller show the message composer – more on this method in a moment.
#import <UIKit/UIKit.h>
#import <MessageUI/MFMessageComposeViewController.h>
@interface TestViewController : UIViewController <MFMessageComposeViewControllerDelegate>
{
UIButton *buttonSMS;
}
@end
SMS View Controller Implementation
The implementation code begins with a very simple loadView method, this is where the view is created and a button defined to initiate sending the SMS:
- (void)loadView
{
[self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
buttonSMS = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonSMS setFrame:CGRectMake(0, 0, 180, 40)];
[buttonSMS setCenter:CGPointMake(160, 208)];
[buttonSMS setTitle:@"Send SMS" forState:UIControlStateNormal];
[buttonSMS addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[[self view] addSubview:buttonSMS];
}
Notice in the button code above the target and action values, when a touch up inside event occurs, the method buttonPressed is called. Inside this method we call a method to send an SMS, passing in the body of the SMS message as well as the phone numbers of the recipients of the message:
- (void)buttonPressed:(UIButton *)button
{
if (button == buttonSMS)
[self sendSMS:@"Body of SMS..." recipientList:[NSArray arrayWithObjects:@"+1-111-222-3333", @"111-333-4444", nil]];
}
Sending an SMS
The last two methods to cover manage creating an instance ofMFMessageComposeViewController to create the SMS content and another method for handling the user interaction with the SMS dialog.
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = bodyOfMessage;
controller.recipients = recipients;
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
[self dismissModalViewControllerAnimated:YES];
if (result == MessageComposeResultCancelled)
NSLog(@"Message cancelled")
else if (result == MessageComposeResultSent)
NSLog(@"Message sent")
else
NSLog(@"Message failed")
}
In the sendSMS method, the first check is to ensure the device supports sending messages. Upon success, the body, recipients and delegate are set. The last step is to present a modal view controller to show the SMS dialog.
Once the user taps either the cancel or send on the SMS dialog, the methodmessageComposeViewController is called, here you can check whether the message was sent, cancelled or failed. This is also the time to dismiss the view controller presented in the previous method.
Build the Project
One last step before you can compile the application, you’ll need to add theMessageUI.framework to your project.
SMS on Simulator
You cannot send SMS messages from within the simulator, if you do, you will see the message shown below:
Send SMS Xcode Project
Subscribe to:
Posts (Atom)