Saturday, March 28, 2015

Add a websocket Connection to android

In this post I will show how to integrate web socket server in to your android application.

This can be use to END-END communication between devices.

First you must download these 3 libraries from autobhan website.
AutobahnAndroid

Create a new project in android studio.





Then add a button in to the activity_my.xml file and edit the xml file.



Now you need to add the library.
go to lib folder in your project window(window in the left)

Copy the autobahn library you downloaded in to lib folder.



Go to android studio click synchronize lib folder

Then add autobahn as a library.



 Go to MyActivity.java file
and add the follwing code

USE ws://echo.websocket.org as websocket link..
Note:- this socket will reply the echo of our message.
       Thanks to:-http://www.websocket.org/echo.html
Keep the cursor in the try block and do the following
Then you will see the following methods are created

onOpen :- Calls when app connect to the web socket server.
onClose :- Calls when app/server close the connection.
onTextMessage :- Calls when you received a text message from the server.

The add the highlighted code
In button's code we call a send method with our message.

Then go to Androidmanifest.xml and add following codes.

Now run the the application.

Outputs


When app starting/Orientation is changing

Your app now connected with server..
Then Press Button you will see following screen.


2 comments: