Thursday, December 30, 2010

Getting started with Apache Axis2

I believe my previous post helped you to setup Apache Axis2 on windows. Now let's have a look at how to host a simple Web service with Apache Axis2.


Start an eclipse project and write a simple java class which will output a string "Hello!!!".

Sample1.java

package webservices.samples;

public class Sample1 {

 public String sayHello(String name) {

  return name;

 }

}


Inside src folder of your eclipse project create a new folder called META-INF and create a new file called services.xml in it.





 
  
 
 webservices.samples.Sample1
 
 


The service element has information about one service, inside service element specify the full qualified class name of your webservice (in this case it is webservices.samples.Sample1). In the child element of service element set the attribute name to the operation name you need to invoke through webservice (in this case it is sayHello)


Using Eclipse build the project and export only the relevant package and the META-INF inside bin folder as an archive file(.aar) to the repository\services folder inside axis2 home folder.


Start Axis2 server by double clicking on axis2server.bat inside bin folder. Now it will show deploying your service.


Now fire up a web browser and paste the following address in address bar http://localhost:8080/axis2/services/. It will list down the deployed services. Now your service should also be in that list.


Generating client to access the service

Goto bin folder inside axis2 home folder using command prompt and run the following command.

wsdl2Java.bat -uri http://localhost:8080/axis2/services/mywebservice?wsdl -o C:\myfile -uw

now go to C:\myfile folder using command prompt and give the following command

ant

Make sure you have set Apache ant bin folder to environment variable path before using this command. It will create a folder called build inside it there will be a folder called lib and mywebservice-test-client.jar will be generated inside it. You must use mywebservice-test-client.jar as an external jar file in your client project. Not only that jar you must add another set of external jar files in to your client project. All those jar files reside in lib folder inside axis2 home. Here I have list them out.


axis2-kernel-1.5.jar
axiom-api-1.2.8.jar
axiom-dom-1.2.8.jar
axiom-impl-1.2.8.jar
commons-logging-1.1.1.jar
wsdl4j-1.6.2.jar
XmlSchema-1.4.3.jar
neethi-2.0.4.jar
axis2-transport-local-1.5.jar
axis2-transport-http-1.5.jar
commons-httpclient-3.1.jar
mail-1.4.jar
commons-fileupload-1.2.jar
woden-api-1.0M8.jar
woden-impl-dom-1.0M8.jar
httpcore-4.0.jar
commons-codec-1.3.jar
geronimo-stax-api_1.0_spec-1.0.1.jar
wstx-asl-3.2.4.jar
axis2-jaxws-1.5.jar
axis2-adb-1.5.4.jar

Now you can write the client code. Build the project and run it. Make sure you have started axis2 server when you run the client.


Cilent.java
package webclient.samples;

import webservices.samples.MywebserviceStub;

public class Client {
 
 public static void main(String args[]){

 try {
 MywebserviceStub stub =new MywebserviceStub("http://localhost:8080/axis2/services/mywebservice");
 System.out.println(stub.sayHello("Hello"));
 }catch (Exception e){
 }
 
 }

}


Note: in axis2 home inside conf folder there is axis2.xml file open it and set hotupdate="true", this will auto update axis2 service whenever you update an already deployed service without restarting the axis2 service.

Setting up Apache Axis2 on windows

Download Apache Axis2 and extract the downloaded zip file to a desired location.


Make two new environment variables set first one's variable name as AXIS2_HOME and variable value as path to Axis2 home folder(in my case it is C:\Users\thilini\Desktop\axis2-1.5.4) and second one's variable name as JAVA_HOME and variabale value as path to Java home folder(in my case it is C:\Program Files\Java\jdk1.6.0_16).


Goto bin folder inside Axis2 home folder and double click on axis2server.bat file to start Axis2 service.


Now it's time to test whether installation is successful or not. Just fire up a web browser and paste the following address in address bar http://localhost:8080/axis2/services/. If installation is successful it will list down a service called "Version".


Wednesday, December 29, 2010

java RMI


Making the Remote Service
Step one: Make a Remote interface
  • Remote interface should extend java.rmi.Remote interface

  • Declare that all methods throw a RemoteException as every remote call is considered risky

  • Arguments and return values of remote methods must be either primitive or serializable(Strings, arrays, collections etc), if passing self defined types be sure to implement serializable interface to the class.

  • Step two: Make a Remote Implementation
  • Implement the Remote interface created earlier.

  • Extend java.rmi.server.UnicastRemoteObject to the class

  • As the super class UnicastRemoteObject's constructor throws a Remote Exception it is necessary to write a no-arg constructor that declares a Remote exception in our class.

  • To make available the remote service to clients register the service with RMI registry

  • Step three: Generate Stubs
  • Compile java files

  • Runrmic on the remote implementation class. To do this use the following command: rmic MyRemoteImplementation. This will create MyRemoteImplementation_Stub.class which is going to be the client helper.

  • Step four: run rmiregistry
  • Open a new terminal and goto the directory where your class files reside using command cd

  • Start rmiregistry using following command: rmiregistry

  • Step five: Start the service
  • open a new terminal and run the service following way: java MyRemoteImplementation

  • Server Code
    Remote interface
    import java.rmi.*;
    public interface MyRemoteInterface extends Remote{ //step 1.1 
    public int doCalc(int a,int b) throws RemoteException; //step 1.2 & step 1.3
    }
    
    Remote service
    import java.net.MalformedURLException;
    import java.rmi.*;
    import java.rmi.server.UnicastRemoteObject;
    
    public class MyRemoteImplementation extends UnicastRemoteObject implements MyRemoteInterface {//step 2.1 & 2.2
     
     public MyRemoteImplementation() throws RemoteException {} //step 2.3
    
     public int doCalc(int a,int b){  
      int result=a+b;
      System.out.println("Returned the result= "+result+" to client!");
      return result;
     }
     
     public static void main(String args[]){
      
      MyRemoteInterface service=null;
      try {
       service = new MyRemoteImplementation();
      } catch (RemoteException e) {
       e.printStackTrace();
      }
      try {
       Naming.rebind("welcome", service); //step 2.4 and be sure to give a name without spaces
      } catch (RemoteException e) {
       e.printStackTrace();
      } catch (MalformedURLException e) {
       e.printStackTrace();
      }
      
     }
    }
    
    
    
    Note: Server should have following three classes to work.
  • MyRemoteInterface.class

  • MyRemoteImplementation.class

  • MyRemoteImplementation_Stub.class

  • How client works?
    Note: Client should have following three classes to work.
  • MyRemoteInterface.class

  • MyRemoteClient.class

  • MyRemoteImplementation_Stub.class

  • Client does a lookup on the RMI registry and RMI registry returns the stub object. Stub pretends to be the real service and let client invokes the method in it.
    Client Code
    import java.rmi.*;
    
    public class MyRemoteClient {
     
     public static void main(String args[]){
      
      new MyRemoteClient().getResult();
      
     }
     
     public void getResult(){
      
    try{
       
       MyRemoteInterface service=(MyRemoteInterface)Naming.lookup("rmi://127.0.0.1/welcome");//Client does 
    //the lookup on the RMI registry
       int result=service.doCalc(1,2);
       System.out.println("hello I got the result "+result);
       
       }catch(Exception e){
        e.printStackTrace();
       }
      
     }
    
    
    }
    
    
    

    Output

    Tuesday, December 28, 2010

    JDBC: creating tables and inserting values to tables dynamically sample code

    I believe my previously written "JDBC" post has given you a basic idea to start JDBC in a windows environment. So here I go again under the same topic but this time the post will be limited to a code. In previous post I have given codes to create a database dynamically and connecting to a database. This code shows how to create tables inside that database and inserting values dynamically into that newly created table.

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.sql.*;
    import java.util.Scanner;
    
    public class Myjdbc {
    
     public static void main(String args[]) {
    
      System.out.println("now we are going to connect with a database ");
    
      try {
    
       Class.forName("com.mysql.jdbc.Driver");
    
       Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "123");
       Statement st = con.createStatement();
    
       System.out.println("connection has been made ");
    
       Scanner scanner = new Scanner(System.in);
       System.out.println("please enter table name ");
       String tableName = scanner.next();
    
       String strr = null;
    
       System.out.println("Enter no of columns you like to use: ");
       int noc = scanner.nextInt();
    
       for (int i = 1; i <= noc; i++) {
        BufferedReader bf = new BufferedReader(new InputStreamReader(
          System.in));
        System.out.println("Enter column name with type ");
        String s1 = bf.readLine();
        if (strr == null) {
         strr = s1;
    
        } else {
         strr = strr + s1;
    
        }
    
       }
    
       st.executeUpdate("create table " + tableName + "(" + strr + ")");
       System.out.println("your table " + tableName
         + " has been created!!!");
    
       ResultSet rs = st.executeQuery("SELECT * FROM " + tableName);
       ResultSetMetaData rsmd = rs.getMetaData();
       int NumOfCol = rsmd.getColumnCount();
       System.out.println("Number of Columns of your table =" + tableName
         + " " + NumOfCol);
       System.out.println("Column names are ");
       for (int i = 1; i <= NumOfCol; i++) {
        System.out.println(rsmd.getColumnName(i));
       }
       String strn = null;
       System.out.println("please enter values you need to insert");
    
       for (int i = 1; i <= NumOfCol; i++) {
        String s5 = scanner.next();
        if (strn == null) {
         strn = s5;
    
        } else
         strn = strn + s5;
    
       }
       System.out.println(strn);
    
       st.executeUpdate("insert into " + tableName + " values" + "("
         + strn + ")");
       System.out.println("your table " + tableName
         + " has been filled!!!");
    
       con.close();
       System.out.println("connection has been colsed ");
    
      }
    
      catch (Exception e) {
    
       System.out.println(e.getMessage());
      }
    
     }
    
    }
    
    
    

    Monday, December 27, 2010

    JDBC with mysql

    What are the pre-requirements for starting JDBC?


    Mysql server can be started on windows using following command

    NET START mysql
    

    Mysql server can be stopped on windows using following command

    NET STOP mysql
    

    There is another way to start stop mysql on windows,right-click MyComputer manage-->Services and Applications-->Services find MySQL and toggle start stop or restart.

    After downloading connector/j the mysql-connector-java-5.1.14-bin.jar file can be used as an external jar file to the JDBC project. Please refer previously written post about adding external jars for java or post for adding external jars in eclipse.

    what is jdbc?

    JDBC(java Database Connectivity) is Java application programming interface that allows the Java programmers to access database management system from Java code.

    Creating a database with jdbc sample code

    package pac1;
    
    import java.io.*;
    import java.sql.*;
    
    public class CreateDatabase {
     public static void main(String[] args) {
      System.out.println("Database creation example!");
      Connection con = null;// Connection is an interface in java.sql package
            // that specifies connection with specific
            // database like MySql. The SQL statements are
            // executed within the context of the Connection
            // interface.
      try {
       Class.forName("com.mysql.jdbc.Driver");// this static method
                 // attempts to load the
                 // class and returns class
                 // instance and takes string
                 // type value (driver) after
                 // that matches class with
                 // given string
       // DriverManager is a class of java.sql package that controls a set
       // of JDBC drivers. Each driver has to be register with this class.
       con = DriverManager.getConnection("jdbc:mysql://localhost:3306",
         "root", "123");// establishes a connection to specified
             // database url
       try {
        // Statement an interface. Statement object executes the SQL
        // statement and returns the result it produces
        Statement st = con.createStatement();// method of Connection
                  // interface. which
                  // returns Statement
                  // object. This method
                  // will compile again
                  // and again whenever
                  // the program runs.
        BufferedReader bf = new BufferedReader(new InputStreamReader(
          System.in));
        System.out.println("Enter Database name:");
        String database = bf.readLine();
        st.executeUpdate("CREATE DATABASE " + database);// method also
                    // executes SQL
                    // statement
                    // that may be
                    // INSERT,
                    // UPDATE OR
                    // DELETE
                    // statement are
                    // used in the
                    // code. It
                    // takes string
                    // types
                    // parameters
                    // for SQL
                    // statement. It
                    // returns int.
        System.out.println("1 row(s) affacted");
        con.close();// disconnecting from the connection, frees all the
           // resources occupied by the database.
       } catch (SQLException s) {
        System.out.print(s.getMessage());
        System.out.println("SQL statement is not executed!");
       }
      } catch (Exception e) {
       e.printStackTrace();
      }
     }
    }
    
    


    Connecting with a database sample code

    import java.sql.*;
    
    public class MysqlConnect{
      public static void main(String[] args) {
        System.out.println("MySQL Connect Example.");
        
        try {
          Class.forName("com.mysql.jdbc.Driver");
          Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest","root","root");
          System.out.println("Connected to the database");
          conn.close();
          System.out.println("Disconnected from database");
       
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    

    Note that newly created databases get saved in C:\ProgramData\MySQL\MySQL Server 5.5\data.

    Tuesday, December 21, 2010

    Network multicasting with C#

    What is multicasting?

    IP multicasting allows an application to send a single packet to a selected subset of devices. The IP multicasting scheme uses a particular range of IP addresses to designate different multicast groups. Each multicast group consists of a group of devices listening to the same IP address. As packets are sent out destined for the multicast group address, each device listening to the address receives them. The IP address range 224.0.0.1 through 239.255.255.255 represents multicast groups


    In C# the Socket class supports IP multicasting by using the SetSocketOption() method of the socket.

    MultiRecv program

    The MultiRecv program creates a UDP socket in the normal way, using the standard Socket class methods. After being added to the multicast group, the socket blocks on a ReceiveFrom() method call, waiting for data to arrive


    MultiRecv.cs

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    class MultiRecv
    {
      public static void Main()
      {
       Socket sock = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp);
       Console.WriteLine("Ready to receive…");
       IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
       EndPoint ep = (EndPoint)iep;
       sock.Bind(iep);
       sock.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,newMulticastOption(IPAddress.Parse("224.100.0.1")));
       byte[] data = new byte[1024];
       int recv = sock.ReceiveFrom(data, ref ep);
       string stringData = Encoding.ASCII.GetString(data, 0, recv);
       Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
       sock.Close();
      }
    }
    
    

    MultiSend program

    MultiSend.cs program is created to send multicast packets across network boundaries. when the multicast packet is sent out, it has a TTL(Time To Live) value of 50, allowing it to traverse up to 50 hops before it is terminated. You can use the MultiRecv program to watch the multicast packet go out on the network.


    MultiSend.cs

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    class NewMultiSend
    {
      public static void Main()
      {
       Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);
       IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051);
       IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
       server.Bind(iep);
       
       byte[] data = Encoding.ASCII.GetBytes("This is a test message");
       server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
                   new MulticastOption(IPAddress.Parse("224.100.0.1")));
       server.SetSocketOption(SocketOptionLevel.IP,
       SocketOptionName.MulticastTimeToLive, 50);
       server.SendTo(data, iep2);
       server.Close();
      }
    }
    
    

    Sunday, December 19, 2010

    IO and String manipulation example java code

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Employee {
    
     String employeeNo;
     String employeeName;
     String groupNo;
     String hourlyRate;
     String hoursWorked;
     String bonusStatus;
     PrintWriter pw;
     BufferedReader br;
    
     public void addEmployee() {
      Scanner scanner = new Scanner(System.in);// reading from console
      System.out.println("Enter name");
      employeeName = scanner.next();
    
      System.out.println("Enter no");
      employeeNo = scanner.next();
    
      System.out.println("Enter group no");
      groupNo = scanner.next();
    
      System.out.println("Enter horly rate");
      hourlyRate = scanner.next();
    
      System.out.println("Enter hours worked");
      hoursWorked = scanner.next();
      int ihw = Integer.parseInt(hoursWorked);// converting a string to a
                // number
      String stri = Integer.toString(ihw);// converting an integer to a string
    
      System.out.println("Enter Bonus status");
      bonusStatus = scanner.next();
      char c = bonusStatus.charAt(0);
    
      try {
       pw = new PrintWriter(new FileWriter("newly.txt", true));// writing
                     // to a file
                     // without
                     // overwriting
      } catch (Exception e) {
       System.out.println(e.getMessage());
      }
      String s = employeeName + "@" + employeeNo + "@" + groupNo + "@"
        + hourlyRate + "@" + hoursWorked + "@" + bonusStatus + "@";// String
                       // concatenation
      pw.write(s);
      pw.flush();
    
     }
    
     public void sortHourlyRate() {
      String l = null;
      String x = null;
      try {
       br = new BufferedReader(new FileReader("newly.txt"));// reading from
                     // a file
    
       while ((l = br.readLine()) != null) {
        x = l;
    
       }
    
       String[] array = x.split("@");// using split method
    
       String[] arr = new String[array.length];
    
       int i = 0;
       int j = 3;
       int k = 0;
    
       while (j < array.length - 2) {
    
        arr[i] = array[j];
        j = j + 6;
        i++;
    
       }
    
       String a = null;
    
       while ((arr[k]) != null) {
    
        if (arr[k + 1] != null) {
         if (a == null) {
          a = arr[k] + "@" + arr[k + 1] + "@";
         } else if (a != null) {
          a = a + arr[k + 1] + "@";
         }
    
        }
    
        System.out.println(a);
        k++;
       }
    
       String[] array2 = a.split("@");
       System.out.println(array2[0]);
       Arrays.sort(array2);
       System.out.println(Arrays.toString(array2));
      }
    
      catch (Exception e) {
       System.out.println(e.getMessage());
      }
     }
    
     public void modifyData() {
    
      String l = null;
      String x = null;
      try {
       br = new BufferedReader(new FileReader("newly.txt"));
    
       while ((l = br.readLine()) != null) {
        x = l;
    
       }
       System.out.println(x);
    
       String[] array = x.split("@");
    
       Scanner scanner = new Scanner(System.in);
       System.out.println("please enter the employee name:");
       String s = scanner.next();
       int hs = s.hashCode();
    
       for (int i = 0; i < array.length; i++) {
    
        if (array[i].hashCode() == hs) {
         System.out.println("please enter the new employee name:");
         s = scanner.next();
         array[i] = s;
    
         System.out.println("please enter the new employee no:");
         s = scanner.next();
         array[i + 1] = s;
    
         System.out.println("please enter the new group no:");
         s = scanner.next();
         array[i + 2] = s;
    
         System.out.println("please enter the new hourly rate:");
         s = scanner.next();
         array[i + 3] = s;
    
         System.out.println("please enter the new hours rate:");
         s = scanner.next();
         array[i + 4] = s;
    
         System.out.println("please enter the new bonus rate:");
         s = scanner.next();
         array[i + 5] = s;
    
        }
       }
    
       String g = null;
       int m = 0;
       for (m = 0; m < array.length; m++) {
        if (g == null) {
         g = array[m] + "@";
        } else if (g != null) {
         g = g + array[m] + "@";
        }
       }
    
       PrintWriter pwd = new PrintWriter(new FileWriter("newly.txt"));
       pwd.write(g);
       pwd.flush();
       System.out.println(g);
    
      }
    
      catch (Exception e) {
       System.out.println(e.getMessage());
      }
    
     }
    
     public static void main(String args[]) {
    
      new Employee().addEmployee();
      new Employee().addEmployee();
      new Employee().addEmployee();
      new Employee().sortHourlyRate();
      new Employee().modifyData();
    
     }
    
    }
    
    
    

    Saturday, December 18, 2010

    Calling main method inside main method java

    Here is the way for $subject.

    import java.util.*;
    
    public class Main {
    
     public static void main(String[] args) {
      System.out.println("Hi I need to call main inside main");  
      System.out.println("Do you need to exit? (y|n)");
      
      Scanner scanner=new Scanner(System.in);
      String s= scanner.next();
      char ans=s.charAt(0);
      
      switch(ans){
      
      case 'y':System.exit(0);break;
      case 'n':String[] argz={"A","B"};
      main(argz);
      
      }
    
     }
    
    }
    
    
    

    Note: if you need to invoke a main method of another class it should be done through the name of that particular class as main is a static method.

    Output

    Thursday, December 16, 2010

    Network Broadcasting with C# further

    This post is related to the previously written post Network Broadcasting with C#.

    Consider the Broadcst.cs and RecvBroadcst.cs programs which were provided in Network Broadcasting with C#. In this post those two programs have slightly modified to achieve a special target described in the next paragraph.

    Suppose a peer to peer environment. When a peer connected with the network it continually listens to one specific port and as well sends a broadcasting message in every 5 seconds to the same specific port to inform it is connected. That broadcasting message will be listened through the modified RecvBroadcst.cs program and it will also store the ip of the sender in an Arraylist.Broadcast message is sent through modified Broadcst.cs program. Program.cs is used to run the two threads.


    RecvBroadcst.cs

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Collections;
    
    class RecvBroadcst
    {
        public void init()
        {
    
            while (true)
            {
                Socket sock = new Socket(AddressFamily.InterNetwork,
                        SocketType.Dgram, ProtocolType.Udp);
                IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
                sock.Bind(iep);
                EndPoint ep = (EndPoint)iep;
                Console.WriteLine("Ready to receive…");
                byte[] data = new byte[1024];
                int recv = sock.ReceiveFrom(data, ref ep);
                string stringData = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
    
                string ip = ep.ToString();
    
                string[] array = ip.Split(':');
    
                ArrayList list = new ArrayList();
    
                Console.WriteLine("sender ip {0} is added to the table!", array[0]);
    
                list.Add(array[0]);
    
                sock.Close();
    
            }
        }
    }
    

    Broadcst.cs

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    
    class Broadcst
    {
        public void init()
        {
    
            while (true)
            {
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                             ProtocolType.Udp);
                IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
                string hostname = Dns.GetHostName();
                byte[] data = Encoding.ASCII.GetBytes(hostname);
                sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                sock.SendTo(data, iep1);
                           
                sock.Close();
                Thread.Sleep(5000);
                
            }
        }
    }
    
    
    

    Program.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Threading;
    
    
        public class Program
        {
            static void Main(string[] args)
            {
               
                Thread RecvBraodcast = new Thread(new RecvBroadcst().init);
                Thread Broadcst = new Thread(new Broadcst().init);
    
                RecvBraodcast.Start();
                Broadcst.Start();
          
                
    
            }
        }
    
               
    
               
    
    

    Run these codes in visual studio.

    output

    Wednesday, December 15, 2010

    Nested Classes Java

    Nested class is a class within a class.A nested class is a member of its outer class.

    Nested classes are divided into two categories

    • static
    • Nested classes that are declared static are simply called static nested classes.
    • non-static
    • Non-static nested classes are called inner classes.

    Nested classes can be declared public, private, protected.

    Why use nested classes

    • Suppose a situation where a class A is only used by another class B, in that situation it is no point of writing two classes separately. Class A can be embedded into class B as a nested class
    • Suppose a situation one of class A's variables is used by class B otherwise that variable can be declared private. In such a case it is more appropriate to nest class B inside class A to protect encapsulation

    Static nested classes

    Static nested classes cannot access member variables of it's outer class directly. it can use them only through an object reference.

    Syntax for creating an object in static object class

    OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
    

    Non Static nested classes or Inner Classes

    Inner classes can access member variables of it's outer class directly even their access modifiers are private.

    Syntax for creating an object in an inner class

    OuterClass.InnerClass innerObject = outerObject.new InnerClass();
    

    A sample code to try out

    public class A { //start of outer class
     
     private int a=100;
     private String b="host";
     
     public class B{ // start of inner class or non static nested class
      
      int e=a;//inner classes can access member variables directly even they are private 
      
     }//End of inner class or non static nested class
     
     public static class C{ //start of static nested class
      
      A ob2 = new A();
      String s =ob2.b;//static nested classes cannot access member variables directly, it should be done through an object of outer class  
      
     } //End of start of static nested class
        
        public static void main(String s[]) {
         A ob1=new A();
         
         A.B ob3=ob1.new B();//inner class object creation
         System.out.println(ob3.e);
         
         A.C ob4=new A.C();//static nested class object creation
         System.out.println(ob4.s);     
                     
        }
    }//End of outer class
    
    

    Tuesday, December 14, 2010

    Network Broadcasting with C#

    What Is Broadcasting?

    IP broadcasting is used by network devices to send a single packet of information that can be accessible by every device on the network. Because TCP communication requires that two devices have a dedicated connection, it is not possible to send broadcast messages in a strictly TCP environment. Instead, UDP packets must be used because that protocol has the capability of sending messages without a specific connection being defined.

    Broadcst.cs

    The Broadcst program creates two separate IPEndPoint objects, one using the IPAddress.Broadcast address and one using a local broadcast address 192.168.1.255. Next, the local hostname of the device is determined using the standard Dns GetHostName() method, and it is sent out in two separate broadcast messages.

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    class Broadcst
    {
      public static void Main()
      {
       Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                    ProtocolType.Udp);
       IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
       IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050);
       string hostname = Dns.GetHostName();
       byte[] data = Encoding.ASCII.GetBytes(hostname);
       sock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast, 1);
       sock.SendTo(data, iep1);
       sock.SendTo(data, iep2);
       sock.Close();
      }
    }
    
    

    RecvBroadcst.cs

    The RecvBroadcst program is a simple UDP program that creates a socket and binds it to all network interfaces on the device, using port 9050, the same port that the Broadcst program uses to send its broadcast messages. After binding the socket to the UDP port, the program attempts to receive two messages sent to the port and displays the message and the sending host address information.

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    class RecvBroadcst
    {
      public static void Main()
      {
       Socket sock = new Socket(AddressFamily.InterNetwork,
               SocketType.Dgram, ProtocolType.Udp);
       IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
       sock.Bind(iep);
       EndPoint ep = (EndPoint)iep;
       Console.WriteLine("Ready to receive…");
       byte[] data = new byte[1024];
       int recv = sock.ReceiveFrom(data, ref ep);
       string stringData = Encoding.ASCII.GetString(data, 0, recv);
       Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString());
       data = new byte[1024];
       recv = sock.ReceiveFrom(data, ref ep);
       stringData = Encoding.ASCII.GetString(data, 0, recv);
       Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString());
       sock.Close();
      }
    }
    
    

    For compilation either can use visual studio or visual studio command prompt. Here have used visual studio command prompt. Open up two Visual Studio Command prompts, one for the RecvBroadcst.cs and other one for the Broadcst.cs

    Compile and run:

    Broadcst

    csc Broadcst.cs
    Broadcst.exe

    RecvBroadcst

    csc RecvBroadcst.cs
    RecvBroadcst.exe

    output

    Sunday, December 12, 2010

    Command Line parameters - Eclipse

    • In Eclipse beside the "Run" button there is a downward arrow. Click on it.
    • In the drop-down menu click on "Run Configurations".
    • It will open a new window "Run Configurations", there select the required project.



    • Goto "Arguments" tab and inside "Program arguments" text area type command-line parameters separated by a space.


    Dealing with external jar files on command prompt

    I had a problem with compiling and running a java file in command line where it imports an external jar files. Here is the solution I've found.

    Compilation

    javac -cp <path to where the source codes resides>;<path to where the jar file resides> Example.java

    run

    java <path to where the source codes resides>;<path to where the jar file resides> Example <command-line arguments if any>

    Note 1:  separator ; for windows and : for unix
    Note 2:  multiple jar files can be used delimited by ;
    Note 3:  . can be used to specify the current directory

    How to run a jar file with command line arguments

    1. Open up a command prompt.
    2. Go to the directory which jar file resides using the command "cd".
    3. Type the following command to execute jar file with command line arguments.
      • java -jar <name of the jar file> <command line argument1> <command line argument2>


    Sunday, December 5, 2010

    Asynchronous Client Server in C#

    AsynchronousSocketListener.cs

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    using StateObjectns;
    
    
    namespace AsynchronousSocketListenerns
    {
    
        public class AsynchronousSocketListener
        {
            // Thread signal.
            public static ManualResetEvent allDone = new ManualResetEvent(false);
    
            public AsynchronousSocketListener()
            {
            }
    
            public static void StartListening()
            {
                // Data buffer for incoming data.
                byte[] bytes = new Byte[1024];
    
                // Establish the local endpoint for the socket.
                // The DNS name of the computer
                // running the listener is "host.contoso.com".
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    
                // Create a TCP/IP socket.
                Socket listener = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);
    
                // Bind the socket to the local endpoint and listen for incoming connections.
                try
                {
                    listener.Bind(localEndPoint);
                    listener.Listen(100);
    
                    while (true)
                    {
                        // Set the event to nonsignaled state.
                        allDone.Reset();
    
                        // Start an asynchronous socket to listen for connections.
                        Console.WriteLine("Waiting for a connection...");
                        listener.BeginAccept(
                            new AsyncCallback(AcceptCallback),
                            listener);
    
                        // Wait until a connection is made before continuing.
                        allDone.WaitOne();
                    }
    
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
    
                Console.WriteLine("\nPress ENTER to continue...");
                Console.Read();
    
            }
    
            public static void AcceptCallback(IAsyncResult ar)
            {
                // Signal the main thread to continue.
                allDone.Set();
    
                // Get the socket that handles the client request.
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);
    
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = handler;
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
            }
    
            public static void ReadCallback(IAsyncResult ar)
            {
                String content = String.Empty;
    
                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;
    
                // Read data from the client socket. 
                int bytesRead = handler.EndReceive(ar);
    
                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(
                        state.buffer, 0, bytesRead));
    
                    // Check for end-of-file tag. If it is not there, read 
                    // more data.
                    content = state.sb.ToString();
                    if (content.IndexOf("<eof>") > -1)
                    {
                        // All the data has been read from the 
                        // client. Display it on the console.
                        Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                            content.Length, content);
                        // Echo the data back to the client.
                        Send(handler, content);
                    }
                    else
                    {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                    }
                }
            }
    
            private static void Send(Socket handler, String data)
            {
                // Convert the string data to byte data using ASCII encoding.
                byte[] byteData = Encoding.ASCII.GetBytes(data);
    
                // Begin sending the data to the remote device.
                handler.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), handler);
            }
    
            private static void SendCallback(IAsyncResult ar)
            {
                try
                {
                    // Retrieve the socket from the state object.
                    Socket handler = (Socket)ar.AsyncState;
    
                    // Complete sending the data to the remote device.
                    int bytesSent = handler.EndSend(ar);
                    Console.WriteLine("Sent {0} bytes to client.", bytesSent);
    
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
    
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
    
            public void init()
            {
               
    
                    StartListening();
                
            }
            
        }
    }
    
    

    AsynchronousClient.cs

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Text;
    using StateObjectns;
    
    namespace AsynchronousClientns
    {
    
        public class AsynchronousClient
        {
            // The port number for the remote device.
            private const int port = 11000;
    
            // ManualResetEvent instances signal completion.
            private static ManualResetEvent connectDone =
                new ManualResetEvent(false);
            private static ManualResetEvent sendDone =
                new ManualResetEvent(false);
            private static ManualResetEvent receiveDone =
                new ManualResetEvent(false);
    
            // The response from the remote device.
            private static String response = String.Empty;
    
            private static void StartClient()
            {
                // Connect to a remote device.
                try
                {
                    // Establish the remote endpoint for the socket.
                    // The name of the 
                    // remote device is "host.contoso.com".
                    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                    IPAddress ipAddress = ipHostInfo.AddressList[0];
                    IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
    
                    // Create a TCP/IP socket.
                    Socket client = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);
    
                    // Connect to the remote endpoint.
                    client.BeginConnect(remoteEP,
                        new AsyncCallback(ConnectCallback), client);
                    connectDone.WaitOne();
    
                    // Send test data to the remote device.
                    Send(client, "This is a test<eof>");
                    sendDone.WaitOne();
    
                    // Receive the response from the remote device.
                    Receive(client);
                    receiveDone.WaitOne();
    
                    // Write the response to the console.
                    Console.WriteLine("Response received : {0}", response);
    
                    // Release the socket.
                    client.Shutdown(SocketShutdown.Both);
                    client.Close();
    
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
    
            private static void ConnectCallback(IAsyncResult ar)
            {
                try
                {
                    // Retrieve the socket from the state object.
                    Socket client = (Socket)ar.AsyncState;
    
                    // Complete the connection.
                    client.EndConnect(ar);
    
                    Console.WriteLine("Socket connected to {0}",
                        client.RemoteEndPoint.ToString());
    
                    // Signal that the connection has been made.
                    connectDone.Set();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
    
            private static void Receive(Socket client)
            {
                try
                {
                    // Create the state object.
                    StateObject state = new StateObject();
                    state.workSocket = client;
    
                    // Begin receiving the data from the remote device.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
    
            private static void ReceiveCallback(IAsyncResult ar)
            {
                try
                {
                    // Retrieve the state object and the client socket 
                    // from the asynchronous state object.
                    StateObject state = (StateObject)ar.AsyncState;
                    Socket client = state.workSocket;
    
                    // Read data from the remote device.
                    int bytesRead = client.EndReceive(ar);
    
                    if (bytesRead > 0)
                    {
                        // There might be more data, so store the data received so far.
                        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
    
                        // Get the rest of the data.
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                            new AsyncCallback(ReceiveCallback), state);
                    }
                    else
                    {
                        // All the data has arrived; put it in response.
                        if (state.sb.Length > 1)
                        {
                            response = state.sb.ToString();
                        }
                        // Signal that all bytes have been received.
                        receiveDone.Set();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
    
            private static void Send(Socket client, String data)
            {
                // Convert the string data to byte data using ASCII encoding.
                byte[] byteData = Encoding.ASCII.GetBytes(data);
    
                // Begin sending the data to the remote device.
                client.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), client);
            }
    
            private static void SendCallback(IAsyncResult ar)
            {
                try
                {
                    // Retrieve the socket from the state object.
                    Socket client = (Socket)ar.AsyncState;
    
                    // Complete sending the data to the remote device.
                    int bytesSent = client.EndSend(ar);
                    Console.WriteLine("Sent {0} bytes to server.", bytesSent);
    
                    // Signal that all bytes have been sent.
                    sendDone.Set();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
    
            public void init()
            {
                
    
                    StartClient();
                
            }
        }
    }
    
    
    
    

    StateObject.cs

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    namespace StateObjectns
    {
    
        // State object for reading client/server data asynchronously
        public class StateObject
        {
            // Client  socket.
            public Socket workSocket = null;
            // Size of receive buffer.
            public const int BufferSize = 1024;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
            // Received data string.
            public StringBuilder sb = new StringBuilder();
        }
    }
    
    

    MainRun.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using StateObjectns;
    using AsynchronousClientns;
    using System.Threading;
    using AsynchronousSocketListenerns;
    
    
    namespace MainRunns
    {
        class Program
        {
            static void Main(string[] args)
            {
                Thread servertr = new Thread(new AsynchronousSocketListener().init);
                Thread clienttr = new Thread(new AsynchronousClient().init);
    
                servertr.Start();
                clienttr.Start();
    
                Console.ReadLine();
    
            }
        }
    }
    AsynchronousSocketListenerns.cs creates a server that receives connection requests from clients. The server is built with an asynchronous socket, so execution of the server application is not suspended while it waits for a connection from a client. The application receives a string from the client, displays the string on the console, and then echoes the string back to the client. The string from the client must contain the string "<eof>" to signal the end of the message.

    AsynchronousClient.cs creates a client that connects to a server. As client is built with an asynchronous socket, execution of the client application is not suspended while the server returns a response. The application sends a string to the server and then displays the string returned by the server on the console.

    StateObject.cs is used for reading client/server data asynchronously.

    MainRunns.cs is used to start a server thread and a client thread.

    OutputScreen

    references : http://msdn.microsoft.com/

    Command Line Parameters C#

    Following code shows how command line parameters can accessed in C#.

    //CommandLine3.cs
    // Commandline arguments: A B C
    using System;
    
    namespace CommandLine3
    {             
            public class CommandLine3
            {
                public static void Main(string[] args)
                {
                    Console.WriteLine("You have entered the following {0} command line arguments:",args.Length);
                    for (int i = 0; i < args.Length; i++)
                    {
                        Console.WriteLine("{0}", args[i]);
                    }
                    Console.ReadLine();
                }
            } 
    }
    
    
    Note that:
    • The Length property is used to obtain the length of the array.
    • Length is a read-only property
    Following expanation will be a guide on building and running the code within Visual Studio.
    • Right-click the project(in the above example CommandLine3 will be the project) and click Properties this will open up Open the configuration Properties window and click Debugging tab.





    • In the Command Line Arguments property, type "A B C" and save the project





    • Run the project, make sure project has set as the startup project(to do this right click on the project and click on set as startup project

    For running the code using command-line use following commands
    • csc CommandLine.cs
    • CommandLine.exe A B C

    output


    references : http://msdn.microsoft.com/

    Saturday, December 4, 2010

    exec() Family System Calls

    The exec family of functions shall replace the current process image with a new process image.

    execl()

    Synopsis

    int execl(const char *path, const char *arg0, const char *arg1, const char *arg2, ... const char *argn, (char *) 0);

    A command (with the path to the command e.g /bin/ls) and the required arguments are passed to the function."arg0" is the command to be executed. Function arguments are null terminated strings(The list of arguments is terminated by NULL).

    Example

    #include <unistd.h>
     main()
     {
        execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
     }
    
    

    execlp()

    A command (path to the command will be resolved by the function itself) and the required arguments are passed to the function."arg0" is the command to be executed.

    Example

    #include <unistd.h>
     main()
     {
        execlp("ls", "ls", "-r", "-t", "-l", (char *) 0);
     }
    
    

    execv()

    Synopsis

    int execv(const char *path, char *const argv[]);

    Same as the execl function except now the arguments will be passed into a null terminated char pointer array."arg[0]" is the command to be executed.

    Example

    #include <unistd.h>
     main()
     {
        char *args[] = {"/bin/ls", "-r", "-t", "-l", (char *) 0 };
      
        execv("/bin/ls", args);
     
     }
    
    

    Friday, December 3, 2010

    Twitter Follow Me Button for Blogger


    1. Copy following HTML code fragment
    2. Add "HTML/JavaScript" gadget and paste the previously copied code in it
    3. Change "http://twitter.com/yourID" to the public twitter profile link

    Note: By changing href attribute inside <a> tag and src attribute inside <img> tag(which will be the relevant icon for the link), it is possible to create a button in blogger to redirect into any required public profile.

    Thursday, December 2, 2010

    fork() System Call

    System call fork() is used to create processes, the newly created process will be the child of the calling process parent. Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces.

    fork() returns a process ID AKA PID, there are three instances;

    1. if PID < 0, fork() returns a negative value, the creation of a child process was unsuccessful.


    2. if PID ==0, fork() returns a zero to the newly created child process.


    3. if PID > 0, fork() returns a positive value, the process ID of the child process, to the parent.


    After a successful call of fork(),unix makes two identical copies of address spaces, one for the parent and the other for the child. Both processes will start their execution at the next statement following the fork() call.



    Since both processes have identical but separate address spaces;
    • Variables initialized before the fork() call have the same values in both address spaces.
    • Modifications done in each process will be independent.
    Example
    #include <signal.h>
    #include <stdio.h>
    
    void main() 
    {
     int pid;
    
     printf("Parent process ID %d \n",getpid());
    
     pid = fork();
    
      if (pid==0) {
       printf("Child process ID %d \n",getpid());
        int x;
        printf("Enter Value : ");
        scanf("%d",&x);
        printf("Entered Value : %d",x);
      } else if (pid > 0) {
       sleep(5);// parent stops execution for 5 seconds
       printf("Parent process ID %d \n",getpid());
    
      }
    
    }
    
    

    Synchronous Client Server Application in C#

    TCP Based Server

    • Establish the local end point for the socket
    • Open a socket using Socket()
    • Name the socket using Bind()
    • Listen for incoming connections using Listen(), parameter inside the method specifies the maximu number of pending connections
    • Accept client connections using Accept(), a new socket is created here but the original socket keeps listen
    • Send, Receive data using Send() and Receive()
    • Close Socket using Close()

    Server.cs

       using System; 
       using System.Net.Sockets; 
       using System.Net; 
       using System.Text; 
    
       public class SocketServer 
       { 
          public static void Main(string [] args) 
          { 
    
             // establish the local end point for the socket 
             IPHostEntry ipHost = Dns.Resolve("localhost"); 
             IPAddress ipAddr = ipHost.AddressList[0]; 
             IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000); 
    
             // create a Tcp/Ip Socket 
             Socket sListener = new Socket(AddressFamily.InterNetwork, 
                                           SocketType.Stream, ProtocolType.Tcp); 
    
             // bind the socket to the local endpoint and 
             // listen to the incoming sockets 
    
             try 
             { 
                sListener.Bind(ipEndPoint); 
                sListener.Listen(10); 
    
                // Start listening for connections 
    
                while (true) 
                { 
                   Console.WriteLine("Waiting for a connection on port {0}",ipEndPoint); 
    
                   // program is suspended while waiting for an incoming connection 
                   Socket handler = sListener.Accept(); 
    
                   string data = null; 
    
                   // we got the client attempting to connect 
                   while(true) 
                   { 
                      byte[] bytes = new byte[1024]; 
    
                      int bytesRec = handler.Receive(bytes); 
    
                      data += Encoding.ASCII.GetString(bytes, 0, bytesRec); 
    
                      if (data.IndexOf("<theend>") > -1) 
                      { 
                         break; 
                      } 
                   } 
    
                   // show the data on the console 
                   Console.WriteLine("Text Received: {0}",data); 
    
                   string theReply = "Thank you for those " + data.Length.ToString() 
                                   + " characters..."; 
                   byte[] msg = Encoding.ASCII.GetBytes(theReply); 
    
                   handler.Send(msg); 
                   handler.Shutdown(SocketShutdown.Both); 
                   handler.Close(); 
                } 
             } 
             catch(Exception e) 
             { 
                Console.WriteLine(e.ToString()); 
             } 
    
          } // end of Main 
       } 
    
    
    

    TCP Based Client

    • Establish a remote endpoint
    • Open a socket using Socket()
    • Connect to the remote host using Connect
    • Send, receive data using Send() and Receive()
    • Close Socket using Close()

    Client.cs

    using System; 
    using Systern.Net.Sockets; 
    using Systern.Net; 
    using Systern.Text; 
    
    public class SocketClient 
    { 
       public static void Main(string [] args) 
       {
    
        // data buffer for incoming data 
        byte[] bytes = new byte[1024]; 
    
        // connect to a Remote device 
        try 
        { 
           // Establish the remote end point for the socket 
           IPHostEntry ipHost = Dns.Resolve("127.0.0.1"); 
           IPAddress ipAddr = ipHost.AddressList[0]; 
           IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000); 
    
           Socket sender = new Socket(AddressFamily.Internetwork, 
                                      SocketType.Stream, ProtocolType.Tcp); 
    
           // Connect the socket to the remote endpoint 
    
              sender.Connect(ipEndPoint); 
    
              Console.WriteLine("Socket connected to {0}", 
              sender.RemoteEndPoint.ToString()); 
    
              string theMessage = "This is a test"; 
    
              byte[] msg = Encoding.ASCII.GetBytes(theMessage+"<theend>"); 
    
              // Send the data through the socket 
              int bytesSent = sender.Send(msg); 
    
              // Receive the response from the remote device 
              int bytesRec = sender.Receive(bytes); 
    
              Console.WriteLine("The Server says : {0}", 
                                Encoding.ASCII.GetString(bytes,0, bytesRec)); 
    
              // Release the socket 
              sender.Shutdown(SocketShutdown.Both); 
              sender.Close(); 
    
        } 
        catch(Exception e) 
        { 
           Console.WriteLine("Exception: {0}", e.ToString()); 
        } 
      } 
    } 
    
    
    

    Fllowing image shows how client and server send and receive data

    TCP Fundamentals





    Monday, November 29, 2010

    System.Net.Sockets.Socket Class

    System.Net.Sockets.Socket Class provides the basic functionality of a socket application.

    • Some important properties of System.Net.Sockets.Socket

    Property Description
    AddressFamily Gets the address family of the socket-the value is from the Socket.AddressFamily enumeration
    Available
    Returns the amount of available data to read
    Blocking
    Gets or sets the value which indicates whether the socket is in blocking mode or not
    Connected
    Returns the value that informs whether the socket is still connected with the remote host
    LocalEndPoint
    Gets the local endpoint
    ProtocolType
    Get the protocol type of the socket
    RemoteEndPoint
    Gets the remote endpoint of a socket
    SocketType
    Gets the type of the socket

    • Some important methods of System.Net.Sockets.Socket

    Method Description
    Accept()
    Creates a new socket to handle the incoming connection request.
    Bind()
    Associates a socket with the local endpoint for listening to incoming connections.
    Close()
    Forces the socket to close itself.
    Connect()
    Establishes a connection with the remote host.
    GetSocketOption()
    Returns the value of a SocketOption.
    IOControl()
    Sets low-level operating modes for the socket. This method provides low-level access to the underlying socket instance of the Socket class.
    Listen()
    Places the socket in listening mode. This method is exclusive to server applications.
    Receive()
    Receives data from a connected socket.
    Poll()
    Determines the status of the socket.
    Select()
    Checks the status of one or more sockets.
    Send()
    Sends data to the connected socket.
    SetSocketOption()
    Sets a SocketOption.
    Shutdown()
    Disables send and receive on a socket.

    Sunday, November 28, 2010

    Publish Source Code in Blogger Using SyntaxHighlighter

    • In blogger under "Design" tab click "Edit HTML".
    • Copy following and paste it just before the </head> tag in the area under "Edit Template".
    • <link href="http://syntaxhighlighter.googlecode.com/svn/trunk/Styles/SyntaxHighlighter.css" rel="stylesheet" type="text/css"></link> <script language="javascript" src="http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js"> <script language='javascript' src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js'/>  </script>
    • Copy following and paste it in the same area as in the second step but this time paste it just before the </body> tag.
    • <script language="javascript"> dp.SyntaxHighlighter.BloggerMode(); dp.SyntaxHighlighter.HighlightAll('code'); </script>
    • Goto http://syntaxhighlighter.googlecode.com/svn/trunk/Styles/SyntaxHighlighter.css and copy the entire stylesheet paste it in the same area as step one and two, but this time paste it just before ]]<.
    • HTML Encode the source code using "HTML-encode a string".
    • Composing a blog post inside the "Edit HTML" editor,when you encounter a place where it is required to add the code snippet copy the encoded source code and paste it in between following tags.
    • <pre name="code" class="Cpp"> ….My code here… </pre>  

    Saturday, November 27, 2010

    Sockets

    Sockets

    • Socket is one end of a two way communication link between two programs running on a network.
    • Data can be passed between different processes by connecting the two sockets together

    Basic socket types

    • Stream Socket
      • Connection oriented sockets
      • Consists of a stream of bytes that can be bi-directional
      • Usage of stream sockets is a more reliable method than the usage of datagram sockets
    • Datagram sockets
      • AKA Connectionless sockets, no explicit connection is established
      • A message is sent to a specified socket and can be received appropriately from the specified socket
      • Usage of datagram sockets is reducing the overhead incurred by establishing an explicit connection

    Row sockets

    • Generalized form of sockets called row sockets
    • Packet is passed directly to the application that needs it bypassing the mechanism by which the computer handles TCP/IP

    Ports

    • Defined to solve the problem of communicating with multiple operations simultaneously

    Sockets composed of
    • IP address of the machine
    • Port no used by TCP application

    Socket numbers are unique across the entire internet as IP address is unique across the internet and the port no is unique on the individual machine. This enables process to communicate with another process across network based entirely on socket number.

    Client Server applications uses sockets

    • Server waits for the connection from the client
    • Client initiates the connection with the server
    • Server should be already running before client tries to connect
    • Client must know the target address and the port no, tries to establish a connection with the server
    • Server accepts the connection
    • Server application creates a new socket to deal specifically with the connected client
    • Server and client communicate by reading from and writing to their respective sockets

    Friday, November 26, 2010

    Visual Studio Command Prompt


    C# codes can be compiled using "Visual Studio Command Prompt". Most of the people facing difficulties when it comes to find this command prompt. It resides in "C:\Windows\System32" as cmd.exe. For windows7 users it is possible to search for it through the start menu typing "visual studio command prompt".

    Assume test.cs,

    How to compile

    csc test.cs

    How to execute

    test.exe

    Tuesday, November 23, 2010

    IP Header


    • Version (Specifies the format of the IP packet header): 4 bits.

    • IHL, Internet Header Length (Specifies the length of the IP packet header in 32 bit words. The minimum value for a valid header is 5): 4 bits.

    • Differentiated Services (This field is defined in RFC 2474 and obsoletes the TOS field): 8 bits.

    • Total length (Contains the length of the datagram). 16 bits.

    • Identification (Used to identify the fragments of one datagram from those of another. The originating protocol module of an internet datagram sets the identification field to a value that must be unique for that source-destination pair and protocol for the time the datagram will be active in the internet system. The originating protocol module of a complete datagram clears the MF bit to zero and the Fragment Offset field to zero): 16 bits.

    • Flags: 3 bits.

    • Fragment Offset (Used to direct the reassembly of a fragmented datagram): 13 bits.

    • TTL, Time to Live (A timer field used to track the lifetime of the datagram. When the TTL field is decremented down to zero, the datagram is discarded): 8 bits.

    • Protocol (This field specifies the next encapsulated protocol): 8 bits.

    • Header checksum (A 16 bit one's complement checksum of the IP header and IP options): 16 bits.

    • Source IP address (IP address of the sender): 32 bits.

    • Destination IP address (IP address of the intended receiver): 32 bits.

    ARP

    ARP (address resolution protocol) is used to translate protocol addresses to hardware interface addresses(mac).

    ARP Header





    • Hardware type: 16 bits.

    • Protocol type: 16 bits.

    • Hardware address length (Length of the hardware address in bytes.): 8 bits.

    • Protocol address length (Length of the protocol address in bytes.): 8 bits.

    • Opcode: 16 bits.

    • Source hardware address: Variable length.

    • Source protocol (mac) address: Variable length.

    • Destination hardware (mac) address.: Variable length.

    • Destination protocol address: Variable length.

    Monday, November 22, 2010

    Wireshark video tutorials

    Wireshark is a free and open source software which is used for packet capturing and network analyzing... Download wireshark: http://www.wireshark.org/

    Here are some good video tutorials to get a basic understand of wireshark software...

    Introduction to Wireshark (Part 1 of 3)



    Cookies and Grabbing Passwords with Wireshark (Part 2 of 3)



    Data Mining using Wireshark (Part 3 of 3)

    Thursday, November 18, 2010

    Bit further into lex

    Consider the lex program given below (line.l) which adds line numbers in front of each line in a given text file and displays the output on standard output.

    The use of lex variables and lex functions

    yytext : The text of the matched pattern is stored in this variable. yytext is a char pointer.

    yyin : Of the type FILE*. This points to the current file being parsed by the lexer.

    yylex() : The function that starts the analysis. It is automatically generated by Lex.

    What if there is no matching pattern to be found?
    Any string matches and default action happens which means all the inputs are going to be printed in a way one at a time.

    %{
    
    int lineno=1;
    
    %}
    
    %%
    
    .*\n { printf("%5d %s",lineno++,yytext); }
    
    %%
    
    main(int argc, char*argv[])
    {
    
    FILE *yyin;
    yyin=fopen(argv[1],"r");
    yylex();
    return 0;
    
    }
    
    


    Compilation process

    lex line.l
    cc lex.yy.c -0 line -lfl

    Executing

    For this program it requires a a file as a command line argument. So a file should be provided in this stage.

    ./line filename

    If it is needed to print the output in a file, just redirect the output to a text file like following.

    ./line > filename

    Thursday, November 11, 2010

    How to add external jar files in eclipse

    1. Inside the "package explorer", Right click on the project which needs to add the external jar file and click on "properties".


    2. In "java build path", inside "Libraries" tab choose the external jar file by clicking on "Add external JARs" button and click "OK".


    Wednesday, November 3, 2010

    Configuring Git on Windows

    Create an account in codaset.com


    Create a project in there

    Download and install following three programs in the given order




    After finishing installations, Open git bash program and type the following command there (skip pass phrasing by entering). This process will generate a key.

    ssh-keygen -C “username@email.com” -t rsa

    (give an email address instead of “username@email.com”)



    The key will be stored in a .ssh folder somewhere, usually in your user folder c:\\Documents and Settings\\Username\\.ssh on XP or c:\\Users\\Username\\.ssh on Windows7

    Upload the key to codaset using the following way.
    Myaccount > SSH keys then click on "upload new"



    Open Git Extensions program

    Click "clone repository"


    Goto codaset account again and click on the project created, copy text under SSH tab

    Now gain go to the clone window, paste it to the text area "repository to clone",give a desired destination and click ok

    Goto the given destination folder and the project will be seen in there

    Do the wanted changes to the project , go to the Git extensions again and open the repository been working on, under the command menu click on commit, stage the wanted files and click on "commit and push" to update in codaset so changes will be visible to everyone.