Monday, September 11, 2017

Socket Programming in Java

Source Code:

client Side:



package learning;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;



public class DailyAdviceClient {
 
 
 private JTextArea incoming;
 private JTextField outgoing;
 private Socket sock;
 private BufferedReader reader;
 private PrintWriter writer;
 public void go() {
  
  JFrame frame =new JFrame("Client");
  JPanel mainPanel=new JPanel();
  incoming =new JTextArea(15,30);
     incoming.setLineWrap(true);
     incoming.setWrapStyleWord(true);
        incoming.setEditable(false);
        JScrollPane jScrollPane=new JScrollPane(incoming);
        jScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        outgoing=new JTextField(20);
        JButton sendButton =new JButton("Send");
        sendButton.addActionListener(new sendButtonListener());
        mainPanel.add(jScrollPane);
        mainPanel.add(outgoing);
        mainPanel.add(sendButton);
        
        
        setUpNetworking();
    
        //IncomingReader is Runnable which override run method
        Thread readerThread =new Thread(new IncomingReader());
        readerThread.start();
  
        frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
        frame.setSize(400, 500);
        frame.setVisible(true);
 }
 private void setUpNetworking() {
  try {
   sock=new Socket("127.0.0.1",6000);
   InputStreamReader streamReader=new InputStreamReader(sock.getInputStream());
   reader=new BufferedReader(streamReader);
   writer =new PrintWriter(sock.getOutputStream());
   System.out.println("Networking established");
   
   
  }catch(IOException e) {
   e.printStackTrace();
  }
  
 }
 
 public class sendButtonListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent arg0) {
   try {
    writer.println(outgoing.getText());
    writer.flush();
    
   }catch(Exception e) {
    e.printStackTrace();
   }
   outgoing.setText("");
   outgoing.requestFocus();
   
  }
  
 }
 public class IncomingReader implements Runnable{

  @Override
  public void run() {
   String message;
   try {
    while((message=reader.readLine())!=null) {
   
  
     incoming.append(message+"\n");
    }
   }catch(Exception e) {
    e.printStackTrace();
   }
   
  }
  
 }
 
 
 
 public static void main(String[] args) {
  DailyAdviceClient adviceServer=new DailyAdviceClient();
  adviceServer.go();
 }
}




Server Side:



 
package learning;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

import multithreading.TheThread;

public class DailyAdviceServer {
 
ArrayList clientOutputStream;
private PrintWriter writer;
public class ClientHandler implements Runnable{

 BufferedReader reader;
 Socket sock;
 /*
  * constructor of clienthandere class
  */
 public ClientHandler( Socket clientSocket) {

  try {
   sock=clientSocket;
   InputStreamReader isReader =new InputStreamReader(sock.getInputStream());
   reader =new BufferedReader(isReader);
   
   
  }catch(Exception e) {
   e.printStackTrace();
  }
  
 }
 
 
 
 @Override
 public void run() {

  String message;
  try {
   while((message=reader.readLine())!=null) {
    System.out.println("read"+message);
    tellEverone(message);
   }
  }catch(Exception e) {
   e.printStackTrace();
  }
  

 }
 
}

public static void main(String[] args) {
 new DailyAdviceServer().go();
 System.out.println(new DailyAdviceServer().clientOutputStream);
}
 

public void go() {
 clientOutputStream=new ArrayList<>();
 try {
  ServerSocket serverSocket=new ServerSocket(6000);
  while(true) {
   Socket clientSocket=serverSocket.accept();
    writer =new PrintWriter(clientSocket.getOutputStream());
   clientOutputStream.add(writer);
   
   Thread t=new Thread(new ClientHandler(clientSocket));
   t.start();
   System.out.println("got a connection"+clientOutputStream.toString());
  }
 }catch (Exception e) {
  e.printStackTrace();
 }
 
}


public void tellEverone(String message) {
 Iterator it=clientOutputStream.iterator();
 while(it.hasNext()) {
  try {
    writer=(PrintWriter)it.next();
   System.out.println(message);
   writer.println(message);
  
   writer.flush();
  }catch(Exception e) {
   e.printStackTrace();
  }
 }
 
}



}


Monday, August 21, 2017

Simple game designing using java swing




Source code
package bouncegame;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;

import javax.swing.Timer;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GamePlay extends JPanel implements ActionListener,KeyListener{
    private Timer timer;
    private  boolean gameplay =false;
    private int score=0;
    private int delay=10;


    private int ballposx=200;
    private int ballposy=200;
    private int ballxdir=-1;
    private int ballydir=-3;
    Timer tm;
    private int playerx=440;


    GamePlay(){



this.requestFocusInWindow(true);

        this.setFocusable(true);
        setFocusTraversalKeysEnabled(false);
        this.addKeyListener(this);     
        tm=new Timer(delay,this);

        tm.start();


    }


    public void paintComponent (Graphics g) {


        super.paintComponent(g);
        //background
        g.setColor(Color.BLACK); 
        g.fillRect(3, 1, 600, 600);
        //border
        g.setColor(Color.blue);
        g.fillRect(0, 0, 3, 600);
        g.fillRect(0, 0, 600, 3);
        g.fillRect(600, 0, 10,600 );

        //paddle
        g.setColor(Color.GREEN);
        g.fillRect(playerx,560 , 50, 8);


        //ball
        g.setColor(Color.ORANGE);
        g.fillOval(ballposx, ballposy, 10, 10);
        //score
        g.setColor(Color.WHITE);
        g.setFont(new Font("sarif",Font.BOLD,20));
        g.drawString("Score "+score, 490, 45);
        //game end
        if(ballposy>600) {
            gameplay=false;
            ballxdir=0;
            ballydir=0;
            g.setColor(Color.RED);
            g.setFont(new Font("sarif",Font.BOLD,20));
            g.drawString("Game Over ", 300, 300);

            g.setFont(new Font("sarif",Font.BOLD,20));
            g.drawString("press Enter to resume ", 250, 330);
        }


        g.dispose();
    }



    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub




    if(gameplay) {

        if(new Rectangle(ballposx,ballposy,12,12).intersects(new Rectangle(playerx,540,50,8))  )
        {
            ballydir=-ballydir;
            score+=10;




        }


        ballposx+=ballxdir;
        ballposy+=ballydir;
        System.out.println(ballposx+" "+ballposy);

        if(ballposx<0) {
            ballxdir=-ballxdir;
        }

        if(ballposy<0) {
            ballydir=-ballydir;

        }

        if(ballposx>580) {
            ballxdir=-ballxdir;
        }

    }


    repaint();

    }

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub




        if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
            if(playerx>=540) {
                playerx=540;
            }
            else
            {
                moveRight();
            }

        }


        if(e.getKeyCode()==KeyEvent.VK_LEFT) {


            if(playerx<=3) {
                playerx=3;
            }
            else
            {
                moveLeft();
            }

        }
        if(e.getKeyCode()==KeyEvent.VK_ENTER) {
            if(gameplay==false) {

                gameplay=true;
                 ballposx=200;
                 ballposy=200;
                 ballxdir=-1;
                 ballydir=-3;
                 score=0;
                 repaint();


            }

        }

    }


    public void moveLeft() {
        // TODO Auto-generated method stub

        gameplay=true;
        playerx-=7;


    }
    public void moveRight() {
        // TODO Auto-generated method stub

        gameplay=true;
        playerx+=7;


    }


    public void keyReleased(KeyEvent e) {}

        public void keyTyped(KeyEvent e) {}

}



Sunday, June 11, 2017

matrix chain multiplication by dynamic programming approach (java implementation)

Matrix multiplication

Source Code

Matrix multiplication

Source Code

        
    
 package dynamic;

public class MatrixChainMultiplication {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("Program is running");
int[] q={2,5,3,5,2,3,5};
int [][] m=matrixChain(p);

System.out.println("Total cost of multiplication matrix:");
for(int i=1;i
    
    

Saturday, June 10, 2017

Java implementation of Floyd -Warshall algorithm for all pair shortest path problem by dynamic programming approach


Source Code:


package dynamic;

public class Floyd {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Program is running...");


int [][]w={
{0,4,11},
{6,0,2},
{3,Integer.MAX_VALUE,0}
};



int [][] d=floydShortestPath(w,3);

for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(d[i][j]+"   ");
}
System.out.println();
}


}

public static int [][] floydShortestPath(int [][] w,int n){

int [][] d=new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){

d[i][j]=w[i][j];

}
}

for(int k=0;k<n;k++){

for(int i=0;i<n;i++){
for(int j=0;j<n;j++){

if(d[i][j]>d[i][k]+d[k][j])
d[i][j]=d[i][k]+d[k][j];
}
}
}


return d;
}



}

java implementation of 0-1 knapsack problem by dynamic programming approach

Source code:

package dynamic;

public class Knapsack {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Program is running");

//input to the function 
int W=5;//knapsack capacity
int n=4;
int [] v={3,4,5,6};
int [] w={2,3,4,5};
 
int [][] c=dynamicKnapsack(W,n,v,w);
for(int i=0;i<=n;i++){
for(int j=0;j<=W;j++){
System.out.print(c[i][j]+"  ");
}
System.out.println();
}
 
solution(c,w,W,n);

}

public static int[][] dynamicKnapsack(int W, int n,int [] v,int w[]){

int [][] c=new int [n+1][W+1];//solution matrix



for(int i=0;i<=n;i++)
c[i][0]=0;

for(int weight=1;weight<=W;weight++)
c[0][weight]=0;

for(int i=1;i<=n;i++){
for(int weight =1;weight<=W;weight++){


if(w[i-1]<=weight){
if(c[i-1][weight] <c[i-1][weight -w[i-1]]+v[i-1])
{
c[i][weight]=c[i-1][weight -w[i-1]]+v[i-1];
}
else 
c[i][weight]=c[i-1][weight];
}
else
c[i][weight]=c[i-1][weight];


}

}


return c;

}
public static void solution (int [][]c,int [] weight,int W,int n){
System.out.println("Maximum Profit ="+c[n][W]);
for(int i=n;i>0;){
for(int w=W;w>0;){
if(c[i][w]!=c[i-1][w]){
System.out.println("Add item "+ (i-1));
i--;
w=w-weight[i];

}
else i--;w--;
}
}


}



}

java implementation of Longest chain subsequence problem by dynamic programming approach

Source code:


package dynamic;




public class LCS {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Program is running ...");

Solution s=longestSequence("abbaab","aabaabb");

for (int i=0;i<=s.m1;i++){
for (int j=0;j<=s.n1;j++){
System.out.print(s.c[i][j]+"  ");

}
System.out.println();
}

System.out.println("The solution matrix b is");
String str;
for (int i=0;i<=s.m1;i++){
for (int j=0;j<=s.n1;j++){
if(s.b[i][j]=='a'){
System.out.print("up"+"\t");
}
if(s.b[i][j]=='u'){
System.out.print("upleft "+"\t");
}
if(s.b[i][j]=='l'){
System.out.print("left"+"\t");
}
}
System.out.println();
}


}
public static Solution longestSequence (String x,String y){
int m=x.length();
int n=y.length();
/*
* solution matrix b
* in whic u=upleft
* a=up
* and l=left
*/

 Solution s=new Solution(m,n);
 
 
 
for(int i=1;i<=m;i++) s.c[i][0]=0;
for(int j=0;j<=n;j++) s.c[0][j]=0;
for (int i=1;i<=m;i++){
for (int j=1;j<=n;j++){
if(x.charAt(i-1)==y.charAt(j-1)){
s.c[i][j]=s.c[i-1][j-1]+1;
s.b[i][j]='u';
}
else if(s.c[i-1][j]>s.c[i][j-1]){
s.c[i][j]=s.c[i-1][j];
s.b[i][j]='a';
}
else 
{
s.c[i][j]=s.c[i][j-1];
s.b[i][j]='l';
}
}
}
return s;
}

}

package dynamic;

public class Solution {

public  int [][]c;
public  char [][]b;
public int m1,n1;
public Solution(int m1,int n1){
this.c=new int [m1+1][n1+1];
this.b=new char[m1+1][n1+1];
this.m1=m1;
this.n1=n1;
}
public Solution(){
}}


Monday, April 24, 2017

Rail Fence Cipher Java implementation



Source Code:


/* railfence cipher*/
package railfence;
import java.util.*;

public class RailFence {


public static void main(String arg[]){


System.out.println("Enter the number of rails:");
Scanner in=new Scanner (System.in);
int rails=in.nextInt();



System.out.println("Enter the plaintext for encryption");
Scanner inn=new Scanner (System.in);
String plaintext=inn.next();

encryption(plaintext,rails);


System.out.println("------------------Decryption process start----------");

System.out.println("Enter the number of rails:");
rails=in.nextInt();
System.out.println("Enter the ciphertext for decryption:");
String ciphertext=in.next();
decryption(ciphertext,rails);

}
public static void encryption(String str,int rails){

boolean checkdown=false;  //check whether it is moving downward or upward
int j=0;
int row=rails;                  // no of row is the no of rails entered by user
int col=str.length();             //column length is the size of string
char[][] a=new char[row][col];
//we create a matrix of a of row *col size

for(int i=0;i<col;i++){  //matrix visitin in rails order and putting the character of plaintext


if(j==0||j==row-1)
checkdown=!checkdown;
a[j][i]=str.charAt(i);
if(checkdown){


j++;
}
else
j--;
}

//visiting the matrix in usual order to get ciphertext
for(int i=0;i<row;i++){
for(int k=0;k<col;k++){
System.out.print(a[i][k]+"  ");
}
System.out.println();
}
String en="";

System.out.println("----------------------");
for(int i=0;i<row;i++){
for(int k=0;k<col;k++){
if(a[i][k]!=0)
en=en+a[i][k];

}

}
System.out.println(en);//printing the ciphertext


}



public static void decryption(String str,int rails){


boolean checkdown=false;
int j=0;
int row=rails;
int col=str.length();
char[][] a=new char[row][col];

//first of all mark the rails position by * in the matrix
for(int i=0;i<col;i++){
if(j==0||j==row-1)
checkdown=!checkdown;



a[j][i]='*';
if(checkdown)j++;
else j--;

}


//now enter the character of cipheetext in the matrix positon that have * symbol
int index=0;

for(int i=0;i<row;i++){
for(int k=0;k<col;k++){


if(a[i][k]=='*'&&index<str.length()){
a[i][k]=str.charAt(index++);




}

}



}

// visit each character in rails order as character are put in the encryption function
for(int i=0;i<row;i++){
for (int k=0;k<col;k++){
System.out.print(a[i][k]+ "\t");
}
System.out.println();
}


checkdown=false;
String s="";
j=0;

for(int i=0;i<col;i++){
if( j==0||j==row-1)
checkdown=!checkdown;


s+=a[j][i];


if(checkdown)j++;
else j--;

}



System.out.print(s);//print the plaintext that was decrypted by rail fence cipher







}
}


Saturday, April 8, 2017

PlayFair Cipher

JAVA IMPLEMENTATION OF PLAYFAIR CIPHER




package playfair;

import java.awt.Point;
import java.util.Scanner;

public class PlayFair {
public static char [][] a=new char[5][5];
public static String alpha="abcdefghijklmnopqrstuvwxyz";

public static void main(String[] args) {
// TODO Auto-generated method stub

System.out.println("Enter the key ");
Scanner in =new Scanner(System.in);
String key=in.nextLine();
setMatrix(key);
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
System.out.println("Enter the message to Encryption(plaintext):");
String plaintext=in.nextLine();
encryption(plaintext);
System.out.println("Enter the message to Decryption");
String ciphertext=in.nextLine();
decryption(ciphertext);
}
public static boolean isRepeat(char c){
for(int i=0;i<5;i++){
for (int j=0;j<5;j++){
if(a[i][j]==c||(a[i][j]=='i'&&c=='j')||(a[i][j]=='j'&&c=='i'))
return true;
}
}
return false;
}
public  static void setMatrix(String str){
int k=0; int p=0,q=0;

//setting the keyword in matrix
loop:{
for(int i=0;i<5;i++){
for( int j=0;j<5;){
char ch=str.charAt(k++);
if(!isRepeat(ch)){
a[i][j++]=ch;
}
if(k==str.length()){
p=i;
q=j;
break loop;
}
}
}
}//looping break
//setting remaining letter in matrix
k=0; 
loop:
{
for(int i=p;i<5;i++){
for(int j=q ;j<5;){
char ch=alpha.charAt(k++);
if(!isRepeat(ch)){
a[i][j++]=ch;
}
if(k==alpha.length())
break loop;
}
q=0;
}
}//loop breaking
}

public static void encryption(String str){
StringBuilder sb=new StringBuilder(str);
for(int i=0;i<sb.length();i+=2){
if(i==sb.length()-1)
sb.append(sb.length()%2==1?'x':"");
else if (sb.charAt(i)==sb.charAt(i+1))
sb.insert(i+1,"x");
}
encode(sb);
}
//function that encode the string
public static void encode(StringBuilder sb){

for (int i=0;i<sb.length();i+=2){
char key1=sb.charAt(i);
char key2=sb.charAt(i+1);
Point key1pos=position(key1);
Point key2pos=position(key2);
//testing if row1 is equal to row2
int row1=key1pos.x;
int row2=key2pos.x;

int col1=key1pos.y;
int col2=key2pos.y;
if(row1==row2){
col1=(key1pos.y+1)%5;
    col2=(key2pos.y+1)%5;
}
else if( col1==col2){
 

row1=(key1pos.x+1)%5;
row2=(key2pos.x+1)%5;
}
else{
int temp=col1;
col1=col2;
col2=temp;
}
sb.setCharAt(i,a[row1][col1]);
sb.setCharAt(i+1,a[row2][col2]);
 
 
 
}
System.out.println(sb);
}
public static void decryption(String str){
StringBuilder sb=new StringBuilder(str);
for (int i=0;i<sb.length();i+=2){
char key1=sb.charAt(i);
char key2=sb.charAt(i+1);
Point key1pos=position(key1);
Point key2pos=position(key2);
//testing if row1 is equal to row2
int row1=key1pos.x;
int row2=key2pos.x;

int col1=key1pos.y;
int col2=key2pos.y;
if(row1==row2){
col1=(key1pos.y-1);
    col2=(key2pos.y-1);
    if(col1==-1) col1=4;
   
    if(col2==-1) col2=4;
    
 
}
else if( col1==col2){
 

row1=(key1pos.x-1);
row2=(key2pos.x-1);
 if(row1==-1) row1=4;
 if(row2==-1) row2=4;
   
    
}
else{
int temp=col1;
col1=col2;
col2=temp;
}
sb.setCharAt(i,a[row1][col1]);
sb.setCharAt(i+1,a[row2][col2]);
 
 
 
}
System.out.println(sb);
}



// function to find the position of character in matrix
public static Point position(char c){
Point p=new Point();

for(int i=0;i<5;i++){
for (int j=0;j<5;j++){
if(a[i][j]==c||(a[i][j]=='i'&&c=='j')||(a[i][j]=='j'&&c=='i'))
{
p.x=i;
p.y=j;
return p;
}
}
}
return null;
}

}

Wednesday, April 5, 2017

Ceaser Cipher Java Implementation

Ceaser Cipher Java Implementation




The Caesar cipher, also known as a shift cipher, is one of the simplest forms of encryption. It is a substitution cipher where each letter in the original message (called the plaintext) is replaced with a letter corresponding to a certain number of letters up or down in the alphabet.
In this way, a message that initially was quite readable, ends up in a form that can not be understood at a simple glance.
For example, here's the Caesar Cipher encryption of a message, using a right shift of 3.
Plaintext:  
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Ciphertext: 
QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
Encryption:  c=(m+k)mod 26
Decryption: m=(c-k+26)mod 26
source code:
package ceaser;


import java.util.Scanner;

public class Ceaser {

 
 
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("Enter the plaintext:");
  Scanner in =new Scanner(System.in);
  String str=in.nextLine();
  Ceaser.encryption(str);
  System.out.println("Enter the ciphertext:");
  str=in.nextLine();
  Ceaser.decryption(str);
  
  

 }
 

 
 public static void encryption(String str){
 String en="";  
  for(int i=0;i<str.length();i++){
   
     char ch = (char) (((int)str.charAt(i) +3 - 97) % 26 + 97);
   
     en +=ch;
   
   
  }
  System.out.println("The ciphertext is:"+en);
  
 }
 public static void decryption(String str){
  
 
  String en="";  
  for(int i=0;i<str.length();i++){
   
     char ch = (char) (((int)str.charAt(i) -3 +26 -97) % 26 + 97);
   
     en +=ch;
   
   
  }
  System.out.println("The ciphertext is:"+en);
 
 
 }
 

}


Output:
Enter the plaintext:
patancampus
The ciphertext is:sdwdqfdpsxv
Enter the ciphertext:
ghimireshankar
The ciphertext is:defjfobpexkhxo

Run your first java program

ØSet up/Install Java
1. Make sure the JDK is installed and that the jdk/bin directory is on the executable path.



2. Updating the PATH Environment Variable



3.Verify Java Installed Correctly

Windows + R = Open Run







Simple Program of Java
In this page, we will learn how to write the simple program of java. We can write a simple hello java program easily after installing the JDK.
To create a simple java program, you need to create a class that contains main method.
Let's understand the requirement first

Requirement for Hello Java Example

For executing any java program, you need to
        Install the JDK if you don't have installed it, download the JDK and install it.
        Set path of the jdk/bin directory.
        create the java program
        compile and run the java program


Creating hello java example


To compile:      javac HelloWorld.java

To execute:     java HelloWorld


Output: HELLO WORLD

Socket Programming in Java

Source Code: client Side: package learning; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event....