Nirutechnolabs

Learning & Integrating web technology and code help directory

How to connect to a memcached server ?

Memcached - Connection


To connect to a Memcached server, you need to use telnet command providing HOST name and PORT number.

Syntax

The basic syntax of Memcached telnet command is as shown below −
$telnet HOST PORT
Here, HOST and PORT are machine IP and port number respectively, on which the Memcached server is running.

Example

The following example shows how to connect to a Memcached server and execute a simple set and get command. Assume that the Memcached server is running on host 127.0.0.1 and port 11211.
$telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
// now store some data and get it from memcached server
set tutorialspoint 0 900 9
memcached
STORED
get tutorialspoint
VALUE tutorialspoint 0 9
memcached
END

Connection from Java Application

To connect the Memcached server from your java program, you need to add the Memcached jar into your classpath. The following program assumes that Memcached server is running on host 127.0.0.1 and port 11211 −

Example

import net.spy.memcached.MemcachedClient;
import java.net.*;


public class MemcachedJava {
   public static void main(String[] args) {
      try{
         // Connecting to Memcached server on localhost
         MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
         System.out.println("Connection to server sucessful.");
         
         // Shutdowns the memcached client
         mcc.shutdown();
         
      }catch(Exception ex){
         System.out.println( ex.getMessage() );
      }
   }
}
This program tries to connect memcached server on IP 127.0.0.1 and port number 11211 using InetSocketAddress.

Output

On compiling and executing the program, memcached client should connect to memcached server listening on port 11211 and the following should be the output −
Connection to server successful.

What is Memcached

What is Memcached ?


Memcached is an open source, high-performance, distributed memory object caching system. This tutorial provides a basic understanding of all the relevant concepts of Memcached needed to create and deploy a highly scalable and performance-oriented system.
Software professionals, students and IT enthusiats who wish to learn and apply the concepts of Memcached in simple and easy steps should read this tutorial.
This tutorial has been designed for absolute beginners and to get best out of it the reader should know the basics of data structures.
Memcached is an open source, high-performance, distributed memory caching system intended to speed up dynamic web applications by reducing the database load. It is a key-value dictionary of strings, objects, etc, stored in the memory, resulting from database calls, API calls, or page rendering.
Memcached was developed by Brad Fitzpatrick for LiveJournal in 2003. However, it is now being used by Netlog, Facebook, Flickr, Wikipedia, Twitter, and YouTube among others.
The key features of Memcached are as follows −
  • It is open source.
  • Memcached server is a big hash table.
  • It significantly reduces the database load.
  • It is perfectly efficient for websites with high database load.
  • It is distributed under Berkeley Software Distribution (BSD) license.
  • It is a client-server application over TCP and/or UDP.

Memcached is not −

  • a persistent data store
  • a database
  • application-specific
  • a large object cache
  • fault-tolerant or
  • highly available

Installing Memcached on Ubuntu

To install Memcached on Ubuntu, go to terminal and type the following commands −
$sudo apt-get update
$sudo apt-get install memcached

Confirming Memcached Installation

To check if Memcached is presently running or not, run the command given below −
$ps aux | grep memcached
This command should show that Memcached is running on the default port11211.
To run Memcached server on a different port, run the command given below −
$memcached -p 11111 -U 11111 -u user -d
It should start the server and listen on TCP port 11111 and UDP port 11111as a daemon process.
This command is explained below −
  • -p is for TCP port number
  • -U is for UDP port number
  • -u is for user name
  • -d runs memcached as daemon process
You can run multiple instances of Memcached server through a single installation.

PhoneGap folder structure for offline app

PhoneGap - App Contents


Offline websites are copied to local hard drive and accessed whenever the user needs to without any internet connection. Likewise, this offline web app will let you create a web application that is downloaded to its entirety to the mobile devices of a user who can access that offline.
An application for this type of app may include app having collection of stories, short tutorials or any other offline content of users' interest, which he/she can read offline even when internet is not available.

Offline App

The following image represents the folder structure for offline app. At root directory it requires only two files, config.xml and index.xml.
Offline PhoneGap App
The config.xml contains app configuration settings which we learnt in previous section. The index.html file contains homepage of web contents.
One important thing to learn here is that all links inside all html files should contain relative path only. That is, no absolute path or base href tag should be there.

Online App

The following image shows folder structure for our app to be in online mode. In online mode, entire web content is loaded from internet website.
Online PhoneGap App
You may notice that data folder is missing in online mode app, because all the files reside on the actual server and are accessible via internet. The index.html file contains actual links as it contains at the web server and all its links are either absolute or used with base href tag.
After you have decided the mode of your app and organized its files in the file structure mentioned above, you need to zip your file with any standard zip tool and save it. We shall use this file in the next section.

Sign Your App

It is essential for any app to be signed by its developers or developing organization to keep things in order. For this reason, you need to sign your app. You may need keytool which is a part of standard java distribution.
Execute the following command in %JAVA_HOME% in your Windows command prompt or Linux Shell −
keytool -genkey -v -keystore my_keystore.keystore 
   -alias TutorialsPoint -keyalg RSA -keysize 2048 -validity 10000


Now we are ready to compile our first web API-based quick mode app. In this final segment, we shall learn about the process of transforming our web contents to an app format, which can be uploaded on online app stores.
PhoneGap accepts user login created on GitHub or using AdobeID. GitHub is a repository service where users can upload their contents and use them by providing their URL references. For example, the content we just created can be uploaded to GitHub and then call it directly to PhoneGap.
The following steps detail how to create an Adobe ID.

Create Adobe ID

Go to www.build.phonegap.com and click on Register
A new window will open as displayed below −
Adobe
Fill in your details and click on sign up. You can now login with the same user id to PhoneGap. By default, this page should lead to PhoneGap console as displayed below −
Adobe PhoneGap
Click ‘Upload a .zip file’ and upload the .zip file we created, which has the entire web content and configurations. You should see the following window after successful upload −
First App
You may instantly see that iOS app has failed its processing as we have not provided any signed key. We are only concentrating on Android and you can see that it has been created by PhoneGap. This app cannot be uploaded to google store as it is not signed by key.
Click on the Android icon and the following screen should appear −
First App2
Click on drop-down option menu next to Android icon that reads No key selected, click on add a key and the following screen should appear −
Keystore
Provide title and alias of your choice and click on Keystore file. Provide the keystore file created in the last section. Then click on 'Rebuild' button next to it.
The app built by this process can be directly uploaded to Google Play. Click on .apk file and you can download your first web-based free app.

How to PhoneGap Setp

PhoneGap - Environment Setup


In this chapter, we will learn how to set up basic environment in order to make apps effortlessly. Though PhoneGap supports offline creation of apps using Cordova command line interface and Github repository mechanism, we shall concentrate on minimum effort procedure.
We assume that you are well versed with web technologies and have your web application ready to be shipped as an app. Because PhoneGap supports only HTML, CSS and JavaScript, it is mandatory that the application should be created using these technologies only.
From a developer’s perspective, an app should have the following items included in its package −
  • Configuration files
  • Icons for app
  • Information or content (built using web technologies)

Configuration

Our web app will need only one configuration file that should be adequate to configure all its necessary settings. Its name is config.xml. This file contains all the necessary information required to compile the app.
Let us see config.xml for our example −
<?xml version = "1.0" encoding = "UTF-8"?>

<widget xmlns = "http://www.w3.org/ns/widgets" 
   xmlns:gap = "http://phonegap.com/ns/1.0" id = "com.tutorialspoint.onlineviewer" version = "1.0">
   
   <name>Tutorials Point</name>
   
   <description>
      Tutorials Point Online Viewer
   </description>
   
   <author href = "http://tutorialspoint.com" email = "contact@tutorialspoint.com">
      Tutorials Point
   </author>
   
   <preference name = "permissions" value = "none"/>
   
   <icon src = "res/icon/android/drawable-ldpi/tp_icon.png" 
      gap:platform = "android" gap:qualifier = "ldpi" />
  
   <icon src = "res/icon/android/drawable-mdpi/tp_icon.png" 
      gap:platform = "android" gap:qualifier = "mdpi" />
  
   <icon src = "res/icon/android/drawable-hdpi/tp_icon.png" 
      gap:platform = "android" gap:qualifier = "hdpi" />
  
   <icon src = "res/icon/android/drawable-xhdpi/tp_icon.png" 
      gap:platform = "android" gap:qualifier = "xhdpi" />
  
   <icon src = "res/icon/android/drawable-xxhdpi/tp_icon.png" 
      gap:platform = "android" gap:qualifier = "xxhdpi" />
   
   <icon src = "res/icon/ios/Icon-72.png" gap:platform = "ios" gap:qualifier = ""/>
   <icon src = "res/icon/ios/icon-57.png" gap:platform = "ios" width = "57" height = "57" />
   <icon src = "res/icon/ios/icon-72.png" gap:platform = "ios" width = "72" height = "72" />
   <icon src = "res/icon/ios/icon-57-2x.png" gap:platform = "ios" width = "114" height = "114" />
   <icon src = "res/icon/ios/icon-72-2x.png" gap:platform = "ios" width = "144" height = "144" />
   
</widget>
All configuration contents are wrapped in <widget> tag. Brief description of these is as follows −
<widget id = ”app_id”>
id is your reserved app-id on various app stores. It is in reverse-domain name style i.e. com.tutorialspoint.onlineviewer etc.
<widget version = "x.y.z">
This is version number of app in x.y.z format where (x,y,z) are positive integers i.e. 1.0.0, it represents major.minor.patch version system.
<name> App Name</name>
This is the name of the app, which will be displayed below the app icon on the mobile screen. Your app can be searched using this name.
<description> My First Web App </description>
This is a brief description of what the app is about, and what it is.
<author> Author_Name </author>
This field contains name of the creator or programmer, generally set to the name of organization which is launching this app.
<preferences name = "permissions" value = "none">
The preferences tag is used to set various options like FullScreen, BackgroundColor and Orientation for app. These options are in name and value pair. For example: name = "FullScreen" value = "true" etc. Because we do not require any of these advance settings, we just put permissions to none.
<icon>
Allows us to add icons to our apps. It can be coded in various ways, but since we are learning short-cut of everything, so here it is. The .src determines the path of icon image. The gap:platform determines for which OS platform this icon is to be used. The gap:qualifier is density that is used by android devices. The iOS devices use width & height parameters.

Icons

There are devices of various sizes having same mobile operating system, so to target an audience of one platform you need to furnish icons of all the mobiles types too. It is important that we prepare icons of exact shapes and sizes as required by particular mobile operating system.
Here we are using the folders res/icon/ios andres/icon/android/drawable-xxxx..
To get this work done fast, you can create a logo of size 1024x1024 and log on to makeappicon.com. This website will help you instantly create logos of all sizes for both android and iOS platform.
App Icons
After providing icon image of size 1024x1024, makeappicon.com should provide the following −

About PhoneGap

PhoneGap 

PhoneGap is a software development framework by Adobe System, which is used to develop mobile applications. To develop apps using PhoneGap, the developer does not require to have knowledge of mobile programming language but only web-development languages like, HTML, CSS, and JScript. PhoneGap produces apps for all popular mobile OS platforms such as iOS, Android, BlackBerry, and Windows Mobile OS etc. In this tutorial we will focus on developing App for Android platform. This tutorial will give you adequate information about how to produce apps quickly using PhoneGap services.

Audience

Programmers who want their website to be available on app either offline or online, may take advantage of this tutorial. This tutorial is designed to give a general view of App building using web technologies. Anybody who is interested to know how to develop Apps using web technologies may use this tutorial.

Prerequisites

It is mandatory that you have knowledge of HTML, CSS and JScript to create website that you might want to put on App. No other programming language is required to use PhoneGap.

Mobile, handhelds and easy-to-carry devices have started a new revolution in software engineering. These small but efficient devices are capable to run applications created with high-end programming languages. People who own these devices tend to use them at their maximum as these devices such as mobile phones, are very convenient to use anytime, anywhere.
The architecture of a mobile device is similar to that of a computer system. It has custom built hardware, firmware, and operating systems.
Mobile
These three items are mostly proprietary and are engineered, developed, and assembled under one flagship organization. Apps (Application Software) are developed both by flagship organization and developers from outside the organization.
A number of well-recognized mobile operating systems are available in the market in both proprietary and open-source categories. Most widely used mobile operating systems are −
  • Android
  • IOS
  • BlackBerry
  • Windows
Mobile Operating System
Every mobile operating system provides their own set of tools and environments to develop apps that will run on them. Application made for one operating system cannot run on any other platform as they are entirely different. Developers tend to cover all major mobile operating systems in order to increase reachability among their users.
Thus it becomes a tedious task to develop an application program that may run on all major OS platforms, keeping its look, feel, and functionality identical on all platforms. For this work, a developer needs to understand all platforms and should have a good understanding of major development tools for different operating systems.

PhoneGap

PhoneGap may be seen as a solution to all problems mentioned above. PhoneGap is a framework that makes the developers develop their apps using standard web APIs for all major mobile operating systems. It is open-source and free.
Developers only need to know web development using HTML, CSS and JavaScript. PhoneGap takes care of rest of the work, such as look and feel of the app and portability among various mobile operating systems.
Mobile OSI
Using PhoneGap, one can create apps for all major mobile operating systems like Apple iOS, Android, BlackBerry, Windows etc. This does not require the developer to have an expertise over any of the above mentioned platforms, neither the developer is required to know programming to code the app from scratch.
PhoneGap allows its users to upload the data contents on website and it automatically converts it to various App files.
In this tutorial, we shall see how to create an app for Apple, android, and windows platform online without using any offline tool.

PHP - Ajax RSS Feed Example

PHP - Ajax RSS Feed Example


RSS

Really Simple Syndication is used to publish often updated information from website like audio, video, images, etc. We can integrate RSS feeds to a website by using Ajax and php. This code demonstrates how to show RSS feeds in our site.

Index.html

Index page should be as follows −
<html>
   <head>
      
      <script>
         function showRSS(str) {
            if (str.length==0) { 
               document.getElementById("output").innerHTML="";
               return;
            }
         
            if (window.XMLHttpRequest) {
               xmlhttp=new XMLHttpRequest();
            }
            else 
            {
               xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  document.getElementById("output").innerHTML=xmlhttp.responseText;
               }
            }
            
            xmlhttp.open("GET","rss.php?q="+str,true);
            xmlhttp.send();
         }
      </script>
      
   </head>
   <body>
      <p>Please Select an option to get RSS:</p>
      
      <form>
         <select onchange="showRSS(this.value)">
            <option value="">Select an RSS-feed:</option>
            <option value="cnn">CNN</option>
            <option value="bbc">BBC News</option>
            <option value="pc">PC World</option>
         </select>
      </form>
      <br>
      
      <div id="output">RSS-feeds</div>
      
   </body>
</html>

rss.php

rss.php has contained syntax about how to get access to rss feeds and return rss feeds to web pages.
<?php
   $q=$_GET["q"];
   
   if($q=="cnn") {
      $xml=("http://rss.cnn.com/rss/cnn_topstories.rss");
   }
   
   elseif($q=="bbc") {
      $xml=("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml");
   }
   
   elseif($q="pcw"){
      $xml=("http://www.pcworld.com/index.rss");
   }
   $xmlDoc = new DOMDocument();
   $xmlDoc->load($xml);
   
   $channel=$xmlDoc->getElementsByTagName('channel')->item(0);
   
   $channel_title = $channel->getElementsByTagName('title')
   ->item(0)->childNodes->item(0)->nodeValue;
   
   $channel_link = $channel->getElementsByTagName('link')
   ->item(0)->childNodes->item(0)->nodeValue;
   
   $channel_desc = $channel->getElementsByTagName('description')
   ->item(0)->childNodes->item(0)->nodeValue;
   
   echo("<p><a href='" . $channel_link . "'>" . $channel_title . "</a>");
   echo("<br>");
   echo($channel_desc . "</p>");
   
   $x=$xmlDoc->getElementsByTagName('item');
   
   for ($i=0; $i<=2; $i++) {
      $item_title=$x->item($i)->getElementsByTagName('title')
      ->item(0)->childNodes->item(0)->nodeValue;
      
      $item_link=$x->item($i)->getElementsByTagName('link')
      ->item(0)->childNodes->item(0)->nodeValue;
      
      $item_desc=$x->item($i)->getElementsByTagName('description')
      ->item(0)->childNodes->item(0)->nodeValue;
      
      echo ("<p><a href='" . $item_link . "'>" . $item_title . "</a>");
      echo ("<br>");
      echo ($item_desc . "</p>");
   }
?>