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







}
}


Socket Programming in Java

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