Search Tutorials

Showing posts with label Network. Show all posts
Showing posts with label Network. Show all posts

Friday, 24 May 2013

C code to calculate Compression Ratio

New network program in C to calculate Compression Ratio. Compile and Run on Turbo C software. Code is given below:

#include<stdio.h>
#include<conio.h>
void main()
{
char *str="the jamia millia islamia and the jamia milliya islamia are different";
int count=0,t,temp=0,i,var=0,var1,start,end,j,k,l,m=0,n;
float comp=0.0;
clrscr();
i=0;
l=strlen(str);
while(str[i]!='\0')
{
    j=i+1;
    while(str[j]!='\0')
    {
        temp=0;
        if(str[i]==str[j])
        {
        start=j;
        count=0;
        while(str[i]==str[j])
        {
            count++;
            i++;
            j++;
            temp=1;
        }
        end=j-1;
        if(count>=3)
        {
        m++;
        printf("%d %d\n",start,end);
        var=var+end-start+1;
        count=0;
        getch();
        }
        }
        else
        {
        if(temp!=1)
        j++;
        }
    }
    if(temp!=1)
    i++;
}
printf("%d %d",m,var);
var1=((l-var)*9)+(m*14);
printf("\nvar=%d",var1);
t=l*8;
n=var1;
comp=(float)n*100/(float)t;
printf("%d",t);
printf("\nCompression ratio is %f",comp);
getch();
}

//Output Of the above program:-

C code to calculate Compression Ratio
Result of compression ratio

For more c programs related to Network, See the Network label. Share and comment to improve this blog.

Related Programs:-

★ RSA Algorithm

★ Encrypt and Decrypt a message using Substitution Cipher

★ Encrypt and Decrypt a message using Vernan Cipher

★ Encrypt and Decrypt a message using Transposition Cipher

★ Encrypt and Decrypt a message using PlayFair Cipher

C code to Encrypt Message using PlayFair (Monarchy) Cipher

C program to implement PlayFair Cipher to encrypt a given message.

#include<stdio.h>
#include<conio.h>
void main()
{
char v,w,ch,string[100],arr[5][5],key[10],a,b,enc[100];
int temp,i,j,k,l,r1,r2,c1,c2,t,var;
FILE * fp;
fp=fopen("sk.txt","r");   //keep message in sk.txt (e.g. jamia)
clrscr();
printf("Enter the key\n");
fflush(stdin);
scanf("%s",&key);
l=0;
while(1)
{
ch=fgetc(fp);
    if(ch!=EOF)
        {
        string[l++]=ch;
        }
    if(ch==EOF)
    break;
}
string[l]='\0';
puts(string);
for(i=0;key[i]!='\0';i++)
{
    for(j=i+1;key[j]!='\0';j++)
    {
    if(key[i]==key[j])
        {
            temp=1;
            break;
        }
    }
}
if(temp==1)
printf("invalid key");
else
{
k=0;
a='a';
//printf("%c",b);
for(i=0;i<5;i++)
{
    for(j=0;j<5;j++)
    {
    if(k<strlen(key))
     arr[i][j]=key[k];
    else if(k==strlen(key))
    {
    b:
    for(l=0;l<strlen(key);l++)
    {
        if(key[l]==a)
        {
  a++;
  goto b;
        }
    }
    arr[i][j]=a;
    if(a=='i')
     a=a+2;
    else
     a++;
    }
     if(k<strlen(key))
     k++;
    }
}
printf("\n");
printf("The matrix is\n");
for(i=0;i<5;i++)
{
    for(j=0;j<5;j++)
    {
     printf("%c",arr[i][j]);
    }
    printf("\n");
}
t=0;
if(strlen(string)%2!=0)
var=strlen(string)-1;
for(i=0;i<var;)
{
    v=string[i++];
    w=string[i++];
    if(v==w)
    {
     enc[t++]=v;
     enc[t++]='$';
    }
    else
    {
    for(l=0;l<5;l++)
        {
            for(k=0;k<5;k++)
            {
      if(arr[l][k]==v||v=='j'&&arr[l][k]=='i')
      {
       r1=l;
       c1=k;
      }
      if(arr[l][k]==w||w=='j'&&arr[l][k]=='i')
      {
       r2=l;
       c2=k;
      }
            }
        }
        if(c1==c2)
        {
  r1++;
  r2++;
  if(r1==5||r2==5)
  {
   r1=0;
   r2=0;
  }
        }
        else if(r1==r2)
        {
  c1++;
  c2++;
  if(c1==5||c2==5)
  {
   c1=0;
   c2=0;
  }
        }
        else
        {
  temp=r1;
  r1=r2;
  r2=temp;
        }
        enc[t++]=arr[r1][c1];
        enc[t++]=arr[r2][c2];
       
    }
}
if(strlen(string)%2!=0)
 enc[t++]=string[var];
enc[t]='\0';
}
printf("The encrypted text is\n");
puts(enc);
getch();
}

Output of the above program:-

C code to encrypt a message using PlayFair (Monarchy) Cipher
Result of PlayFair (Monarchy) Cipher 

Related Programs:-

RSA Algorithm

Encrypt and Decrypt a message using Substitution Cipher

Encrypt and Decrypt a message using Vernan Cipher

Encrypt and Decrypt a message using Transposition Cipher

Calculate compression ratio

C code to Encrypt & Decrypt Message using Transposition Cipher

C program to implement Transposition Cipher to encrypt and decrypt a given message. This program is tested on Turbo C software.

#include<stdio.h>
#include<string.h>

void cipher(int i,int c);
int findMin();
void makeArray(int,int);

char arr[22][22],darr[22][22],emessage[111],retmessage[111],key[55];
char temp[55],temp2[55];
int k=0;

int main()
{
  char *message,*dmessage;

  int i,j,klen,emlen,flag=0;
  int r,c,index,min,rows;
  clrscr();

  printf("Enetr the key\n");
  fflush(stdin);
  gets(key);

  printf("\nEnter message to be ciphered\n");
  fflush(stdin);
  gets(message);

  strcpy(temp,key);
  klen=strlen(key);

  k=0;
  for(i=0; ;i++)
  {
    if(flag==1)
    break;

    for(j=0;key[j]!=NULL;j++)
    {
      if(message[k]==NULL)
       {
         flag=1;
         arr[i][j]='-';
       }
       else
       {
       arr[i][j]=message[k++];
       }
     }
  }
  r=i;
  c=j;

  for(i=0;i<r;i++)
  {
    for(j=0;j<c;j++)
    {
    printf("%c ",arr[i][j]);
    }
    printf("\n");
  }

k=0;

  for(i=0;i<klen;i++)
  {
   index=findMin();
   cipher(index,r);
  }

   emessage[k]='\0';
   printf("\nEncrypted message is\n");
   for(i=0;emessage[i]!=NULL;i++)
   printf("%c",emessage[i]);

   printf("\n\n");
   //deciphering

   emlen=strlen(emessage);
   //emlen is length of encrypted message

   strcpy(temp,key);

   rows=emlen/klen;
   //rows is no of row of the array to made from ciphered message
   rows;
   j=0;


   for(i=0,k=1;emessage[i]!=NULL;i++,k++)
    {
      //printf("\nEmlen=%d",emlen);
      temp2[j++]=emessage[i];
      if((k%rows)==0)
       {
       temp2[j]='\0';
       index=findMin();
       makeArray(index,rows);
       j=0;
       }
    }

    printf("\nArray Retrieved is\n");

     k=0;
     for(i=0;i<r;i++)
     {
    for(j=0;j<c;j++)
    {
    printf("%c ",darr[i][j]);
    //retrieving message
    retmessage[k++]=darr[i][j];

    }
    printf("\n");
     }
       retmessage[k]='\0';

     printf("\nMessage retrieved is\n");

     for(i=0;retmessage[i]!=NULL;i++)
     printf("%c",retmessage[i]);

  getch();
  return(0);
}

void cipher(int i,int r)
{
  int j;
  for(j=0;j<r;j++)
  {
    {
    emessage[k++]=arr[j][i];
    }
  }
 // emessage[k]='\0';
}

void makeArray(int col,int row)
{
 int i,j;

    for(i=0;i<row;i++)
       {
       darr[i][col]=temp2[i];
       }
}

int findMin()
{
  int i,j,min,index;

       min=temp[0];
       index=0;
       for(j=0;temp[j]!=NULL;j++)
       {
    if(temp[j]<min)
      {
      min=temp[j];
      index=j;
      }
       }

      temp[index]=123;
       return(index);
}

Output of the above program:-

C code to encrypt and decrypt a message using Transposition Cipher
Encrypted Message using Transposition Cipher

C code to encrypt and decrypt a message using Transposition Cipher
Decrypted Message using Transposition Cipher

For more c programs related to Network, See the Network label. Share and comment to improve this blog.

Related Programs:-

Encrypt and Decrypt a message using PlayFair Cipher

Calculate compression ratio

Java code to implement RSA Algorithm

Java code to implement MD5 Algorithm

Java code to send and receive Text or Image File

C code to Encrypt & Decrypt Message using Vernam Cipher

Check out new C program to implement Vernam Cipher to encrypt and decrypt a given message on Turbo C software. Code is given below:

#include<stdio.h>

char arr[26][26];
char message[22],key[22],emessage[22],retMessage[22];
int findRow(char);
int findColumn(char);
int findDecRow(char,int);

int main()
{
 int i=0,j,k,r,c;
 clrscr();
 k=96;

 for(i=0;i<26;i++)
 {
   k++;
   for(j=0;j<26;j++)
   {
    arr[i][j]=k++;
    if(k==123)
    k=97;
   }
 }

 printf("\nEnter message\n");
 gets(message);
 printf("\nEnter the key\n");
 gets(key);
 // Encryption

 for(i=0;key[i]!=NULL;i++)
 {
   c=findRow(key[i]);
   r=findColumn(message[i]);
   emessage[i]=arr[r][c];
 }
 emessage[i]='\0';

 printf("\n Encrypted message is:\n\n");

 for(i=0;emessage[i]!=NULL;i++)
 printf("%c",emessage[i]);

 //decryption

 for(i=0;key[i]!=NULL;i++)
 {
    c=findColumn(key[i]);
    r=findDecRow(emessage[i],c);
    retMessage[i]=arr[r][0];
  }
  retMessage[i]='\0';
  printf("\n\nMessage Retrieved is:\n\n");
  for(i=0;retMessage[i]!=NULL;i++)
  printf("%c",retMessage[i]);
 getch();
 return(0);
}
int findRow(char c)
{
  int i;
  for(i=0;i<26;i++)
  {
   if(arr[0][i]==c)
   return(i);
  }
}

int findColumn(char c)
{
  int i;
  for(i=0;i<26;i++)
  {
   if(arr[i][0]==c)
   return(i);
  }
}

int findDecRow(char c,int j)
{
  int i;
  for(i=0;i<26;i++)
  {
   if(arr[i][j]==c)
   return(i);
  }
}

//Output Of the above program:-

C code to encrypt and decrypt a message using Vernam Cipher
Result of Vernam Cipher

For more c programs related to Network, See the Network label. Share and comment to improve this blog.

Related Programs:-

★ Encrypt and Decrypt a message using Transposition Cipher

★ Encrypt and Decrypt a message using PlayFair Cipher

★ Calculate compression ratio

★ Java code to implement RSA Algorithm

★ Java code to implement MD5 Algorithm

C code to Encrypt & Decrypt Message using Substitution Cipher

Here, we have given C program to implement Substitution Cipher to encrypt and decrypt a given message. Compile and Run it on Turbo C.

#include<stdio.h>

int main()
{
  char *message,*emessage,*dmessage;
  int i,j=0,k,key,temp;
  clrscr();

  printf("\nEnter the key\n");
  scanf("%d",&key);
  key=key%26;
  printf("\nEnter message\n");
  fflush(stdin);
  gets(message);

  for(i=0;message[i]!=NULL;i++)
  message[i]=tolower(message[i]);

  for(i=0;message[i]!=NULL;i++)
  {
  //printf("%c ",message[i]);
    if(message[i]==' ')
    emessage[j++]=message[i];

    else
        {

       if(message[i]>=48 && message[i]<=57)
       {
        temp=message[i]+key;
         if(temp>57)
         emessage[j++]=48+(temp-58);
         else
         emessage[j++]=temp;
       }
       else
           {
        if(message[i]>=97 && message[i]<=123)
          {
           temp=message[i]+key;
           if(temp>122)
             emessage[j++]=97+(temp-123);
           else
             emessage[j++]=temp;
           }
         else
              emessage[j++]=message[i];
        }

              // printf("%c ",emessage[j]);
    }

  }

  emessage[j]='\0';
  printf("\n\n\nEncrypted message is\n\n");
  for(i=0;emessage[i]!=NULL;i++)
  printf("%c",emessage[i]);
//  printf("\n end");

   for(i=0,j=0;emessage[i]!=NULL;i++)
   {

      if(emessage[i]==' ')
     dmessage[j++]=emessage[i];
      else
     {
     if(emessage[i]>=48 && emessage[i]<=57)
        {
         temp=emessage[i]-key;
         if(temp<48)
         dmessage[j++]=58-(48-temp);
         else
         dmessage[j++]=temp;
        }
      else
         {
        if(emessage[i]>=97 && emessage[i]<=123)
          {
           temp=emessage[i]-key;
           if(temp<97)
           dmessage[j++]=123-(97-temp);
           else
           dmessage[j++]=temp;
          }
         else
          dmessage[j++]=emessage[i];
         }
     }
   }
   dmessage[j]='\0';
  printf("\n\n\nRetrieved message is\n\n");
  for(i=0;dmessage[i]!=NULL;i++)
  printf("%c",dmessage[i]);
  getch();
  return(0);
}

//Output Of the above program:-

C code to Encrypt and Decrypt a message using Substitution Cipher
Substitution Cipher Result


For more c programs related to Network, Check the Network label. Share and comment to improve this blog.

Related Programs:-

★ Encrypt and Decrypt a message using Vernan Cipher

★ Encrypt and Decrypt a message using Transposition Cipher

★ Encrypt and Decrypt a message using PlayFair Cipher

★ Calculate compression ratio

★ Java code to implement RSA Algorithm

Tuesday, 23 April 2013

C code to implement RSA Algorithm(Encryption and Decryption)

C program to implement RSA algorithm. The given program will Encrypt and Decrypt a message using RSA Algorithm.

#include<stdio.h> 
#include<conio.h> 
#include<stdlib.h> 
#include<math.h> 
#include<string.h> 

long int p,q,n,t,flag,e[100],d[100],temp[100],j,m[100],en[100],i; 
char msg[100]; 
int prime(long int); 
void ce(); 
long int cd(long int); 
void encrypt(); 
void decrypt(); 
void main() 
{ 
clrscr(); 
printf("\nENTER FIRST PRIME NUMBER\n"); 
scanf("%d",&p); 
flag=prime(p); 
if(flag==0) 
{ 
    printf("\nWRONG INPUT\n"); 
    getch(); 
    exit(1); 
} 
printf("\nENTER ANOTHER PRIME NUMBER\n"); 
scanf("%d",&q); 
flag=prime(q); 
if(flag==0||p==q) 
{ 
    printf("\nWRONG INPUT\n"); 
    getch(); 
    exit(1); 
} 
printf("\nENTER MESSAGE\n"); 
fflush(stdin); 
scanf("%s",msg); 
for(i=0;msg[i]!=NULL;i++) 
m[i]=msg[i]; 
n=p*q; 
t=(p-1)*(q-1); 
ce(); 
printf("\nPOSSIBLE VALUES OF e AND d ARE\n"); 
for(i=0;i<j-1;i++) 
printf("\n%ld\t%ld",e[i],d[i]); 
encrypt(); 
decrypt(); 
getch(); 
} 
int prime(long int pr) 
{ 
int i; 
j=sqrt(pr); 
for(i=2;i<=j;i++) 
{ 
    if(pr%i==0) 
    return 0; 
} 
return 1; 
} 
void ce() 
{ 
int k; 
k=0; 
for(i=2;i<t;i++) 
{ 
    if(t%i==0) 
    continue; 
    flag=prime(i); 
    if(flag==1&&i!=p&&i!=q) 
    { 
        e[k]=i; 
        flag=cd(e[k]); 
        if(flag>0) 
        { 
            d[k]=flag; 
            k++; 
        } 
        if(k==99) 
        break; 
    } 
} 
} 
long int cd(long int x) 
{ 
long int k=1; 
while(1) 
{ 
    k=k+t; 
    if(k%x==0) 
    return(k/x); 
} 
} 
void encrypt() 
{ 
long int pt,ct,key=e[0],k,len; 
i=0; 
len=strlen(msg); 
while(i!=len) 
{ 
    pt=m[i]; 
    pt=pt-96; 
    k=1; 
    for(j=0;j<key;j++) 
    { 
        k=k*pt; 
        k=k%n; 
    } 
    temp[i]=k; 
    ct=k+96; 
    en[i]=ct; 
    i++; 
} 
en[i]=-1; 
printf("\nTHE ENCRYPTED MESSAGE IS\n"); 
for(i=0;en[i]!=-1;i++) 
printf("%c",en[i]); 
} 
void decrypt() 
{ 
long int pt,ct,key=d[0],k; 
i=0; 
while(en[i]!=-1) 
{ 
    ct=temp[i]; 
    k=1; 
    for(j=0;j<key;j++) 
    { 
        k=k*ct; 
        k=k%n; 
    } 
    pt=k+96; 
    m[i]=pt; 
    i++; 
} 
m[i]=-1; 
printf("\nTHE DECRYPTED MESSAGE IS\n"); 
for(i=0;m[i]!=-1;i++) 
printf("%c",m[i]); 
}

Output ff the above program:-

C code to implement RSA (Encryption and Decryption)
RSA Inputs

C code to implement RSA (Encryption and Decryption)
RSA Result

Related Programs:-

Encrypt and Decrypt a message using Substitution Cipher

Encrypt and Decrypt a message using Vernan Cipher

Encrypt and Decrypt a message using Transposition Cipher

Encrypt and Decrypt a message using PlayFair Cipher

Calculate compression ratio

Wednesday, 17 April 2013

Implementation of RSA Algorithm(Encryption and Decryption) in Java

Here, we have given Java program to encrypt and decrypt a given message using RSA algorithm. Open Command Prompt and compile & Run. RSA algorithm is used to changing message that no one can understand the communication between sender and receiver. Sender and Receiver have public and private key and they can only understand message.


import java.math.BigInteger;
import java.util.Random;
import java.io.*;
 
public class RSA {

    private BigInteger p;
    private BigInteger q;
    private BigInteger N;
    private BigInteger phi;
    private BigInteger e;
    private BigInteger d;
    private int bitlength = 1024;
    private int blocksize = 256; //blocksize in byte
    
    private Random r;
     public RSA() {
        r = new Random();
        p = BigInteger.probablePrime(bitlength, r);
        q = BigInteger.probablePrime(bitlength, r);
        N = p.multiply(q);
          
        phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
        e = BigInteger.probablePrime(bitlength/2, r);
        
        while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0 ) {
            e.add(BigInteger.ONE);
        }
 d = e.modInverse(phi); 
    }
    
    public RSA(BigInteger e, BigInteger d, BigInteger N) {
        this.e = e;
        this.d = d;
        this.N = N;
    }
    
    public static void main (String[] args) throws IOException
{
        RSA rsa = new RSA();
        DataInputStream in=new DataInputStream(System.in); 
        String teststring ;
        System.out.println("Enter the plain text:");
        teststring=in.readLine();
        System.out.println("Encrypting String: " + teststring);
        System.out.println("String in Bytes: " + bytesToString(teststring.getBytes()));

        // encrypt
        byte[] encrypted = rsa.encrypt(teststring.getBytes());                  
        System.out.println("Encrypted String in Bytes: " + bytesToString(encrypted));
        
        // decrypt
        byte[] decrypted = rsa.decrypt(encrypted);      
        System.out.println("Decrypted String in Bytes: " +  bytesToString(decrypted));
        
        System.out.println("Decrypted String: " + new String(decrypted));
        
    }

   private static String bytesToString(byte[] encrypted) {
        String test = "";
        for (byte b : encrypted) {
            test += Byte.toString(b);
        }
        return test;
    }
    
 //Encrypt message
     public byte[] encrypt(byte[] message) {     
        return (new BigInteger(message)).modPow(e, N).toByteArray();
    }
      
// Decrypt message
    public byte[] decrypt(byte[] message) {
        return (new BigInteger(message)).modPow(d, N).toByteArray();
    } 
}


For more programs related to Network, Check Network Label. Share and comment to improve this blog.

Implementation of MD5 or SHA Algorithm in Java

This is a general Java program to implement Hash Algorithm which can be used in Android as well. Generate Hash of any message by using your given Algorithm. Just pass message in generateHash(String message) method to create hash.

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaMD5Hash {

    public static void main(String[] args) {
          
            System.out.println("For null " + generateHash(""));

            System.out.println("For simple text "+ generateHash("This is my text"));
          
            System.out.println("For simple numbers " + generateHash("12345"));
    }
  
  
    public static String generateHash(String input) {
      
        String md5 = null;
      
        if(null == input) return null;
      
        try {
          
        //Create MessageDigest object for MD5 or pass SHA-1
        MessageDigest digest = MessageDigest.getInstance("MD5");
      
        //Update input string in message digest
        digest.update(input.getBytes(), 0, input.length());

        //Converts message digest value in base 16 (hex)
        md5 = new BigInteger(1, digest.digest()).toString(16);

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();
        }
        return md5;
    }
}

Pass your algorithm name("SHA-1", "MD5", "SHA-256", or "SHA-512") as a parameter in MessageDigest.getInstance(String algoName) and get the hash result. Algorithm name is not case sensitive, so you can pass mD5 or Md5.

Output Result:-

Implementation of MD5 or SHA Algorithm in Java


Set algorithm or make it dynamic and than run on command prompt. Share and comment if you like this post.

Related Programs:-

★ Java code to send and receive Text or Image File

★ Encrypt and Decrypt a message using Transposition Cipher

★ Encrypt and Decrypt a message using PlayFair Cipher

★ Calculate compression ratio

★ Java code to implement RSA Algorithm

Client Server Java code to send Text or Image File

Java program to send text or image file from client to server(receiver). In this program, more than one client can send text or image file to server. Run client and server program using command prompt, Both side GUI will open for communication.

Sender Program

import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

class Client implements ActionListener
{

    Socket s;
    DataInputStream din;
    DataOutputStream dout;
    String str;

//*******************************Client1 GUI*********************************//

    TextField tf;
    TextArea ta;
    Label lb;
    Button b;

    public Client()
    {

    Frame f=new Frame("Client");
    f.setLayout(new FlowLayout());
    f.setBackground(Color.orange);
    tf=new TextField(15);
    ta=new TextArea(12,20);
    ta.setBackground(Color.white);
    lb=new Label("Enter File Name To Be Send");
    b=new Button("Send");
    f.add(lb);
    f.add(tf);
    f.add(b);
    f.add(ta);
    ta.setBounds(200,200,10,10);
    f.addWindowListener(new W1());
    b.addActionListener(this);
    f.setSize(300,400);
    f.setLocation(300,300);
    f.setVisible(true);
    f.validate();

//*********************************GUI END*******************************//   



//********************************Creating Connection*********************//   


        try {   
        s=new Socket("localhost",7860);
        System.out.println(s);
        din=new DataInputStream(s.getInputStream());
        dout=new DataOutputStream(s.getOutputStream());
            }catch(Exception e)
                          {
                             System.out.println(e);
                          }
     
        }

    private class W1 extends WindowAdapter
     {
          public void windowClosing(WindowEvent we) 
          {
           System.exit(0);
          }
     }

//********************************************************************//

    public void actionPerformed(ActionEvent ae) 
     {
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      
          String fileName;
          if(ae.getSource()==b)
           {   
            fileName=tf.getText();

//*******************Coading for image transfer**********************//       
  
        int flag=0,i;
        String extn="";
            for(i=0;i<fileName.length();i++)
            {
                if(fileName.charAt(i)=='.' || flag==1)
                {
                flag=1;
                extn+=fileName.charAt(i);
                }
            }   
       
            if(extn.equals(".jpg") || extn.equals(".png"))
                {
                try{
               
                    File file = new File(fileName);
                    FileInputStream fin = new FileInputStream(file);   
                    dout.writeUTF(fileName);
                    System.out.println("Sending image...");
                    byte[] readData = new byte[1024];

                    while((i = fin.read(readData)) != -1)
                            {
                            dout.write(readData, 0, i);
                            }
                            System.out.println("Image sent");
                            ta.appendText("\nImage Has Been Sent");
                            fin.close();
                    }catch(IOException ex)
                      {System.out.println("Image ::"+ex);}
           
//*****************************Text File********************************//
                }               
            else
            {
           
            try{
            FileInputStream fstream = new FileInputStream(fileName);
              // Get the object of DataInputStream
              DataInputStream in = new DataInputStream(fstream);
              BufferedReader bcr = new BufferedReader(new InputStreamReader(in));
  
            dout.writeUTF(fileName);
            System.out.println("Sending File" + fileName);
            String s1;
                    ta.appendText("\n");
                    while((s1=bcr.readLine())!=null)
                    {
                    System.out.println(""+s1);
                    ta.appendText(s1+"\n");
                    dout.writeUTF(s1);
                    dout.flush();
                    Thread.currentThread().sleep(500);       
                
                    }
                }catch(Exception e){System.out.println("Enter Valid File Name");}
            }
         }
        }

    public static void main(String ar[])
    {
    Client object=new Client();
    }
}


Receiver program

import java.io.*;
import java.net.*;

class Server
{
static int i=0; 
private static int maxcon=0;
   
    public static void main(String args[])
    {
    try
        {
        ServerSocket ss;
        Socket s;

        System.out.println("Server Started");
        ss=new ServerSocket(7860);

            while((i++ < maxcon) || (maxcon == 0))
            {
            doComms connection;
            s=ss.accept();
            System.out.println(s);
            System.out.println("Client "+i+"  Connected");
            doComms conn_c= new doComms(s);
            Thread t = new Thread(conn_c);
            t.start();
            }
        } catch (IOException ioe) {
                                System.out.println("IOException on socket listen: " + ioe);
                                ioe.printStackTrace();
                                  }
                            
    }
}


class doComms implements Runnable 
{
    private Socket s;
   
    doComms(Socket s)
    {
      this.s=s;
    }

    public void run () 
    {

        try {
        // Get input from the client
            DataInputStream dis = new DataInputStream (s.getInputStream());
            PrintStream out1 = new PrintStream(s.getOutputStream());

            String str,extn="";
            str=dis.readUTF();
            System.out.println("\n"+str);
            int flag=0,i;
            
                for(i=0;i<str.length();i++)
                {
                    
                    if(str.charAt(i)=='.' || flag==1)
                    {
                    flag=1;
                    extn+=str.charAt(i);
                    }
                }
        
        
//**********************reading image*********************************//            
            
                if(extn.equals(".jpg") || extn.equals(".png"))
                  {            
                    File file = new File("RecievedImage"+str);
                    FileOutputStream fout = new FileOutputStream(file);
             
                    //receive and save image from client
                    byte[] readData = new byte[1024];
                    while((i = dis.read(readData)) != -1)
                    {
                        fout.write(readData, 0, i);
                        if(flag==1)
                        {
                        System.out.println("Image Has Been Received");
                        flag=0;
                        }
                    }
                fout.flush();
                fout.close();
 
            
            
//****************************Reading Other Files******************//            
                  }
                else
                {
                    FileWriter fstream = new FileWriter("ReceivedFile"+ str);
                    PrintWriter out=new PrintWriter(fstream);

                    do
                    {
                    str=dis.readUTF();
                    System.out.println(" "+str);
                    out.println(str);
                    out.flush();
                    if(str==null)break;
   
                    }while(true);
        
                    System.out.println("One File Received");
                    out.close();
                }
            } catch (IOException ioe) {
                System.out.println("");
                                      }
    }

}


If you have any doubt than comment and Share to improve this blog.

Related Programs:-

★ Java code to implement RSA Algorithm

★ Java code to implement MD5 Algorithm


★ C code to implement RSA Algorithm

★ Encrypt and Decrypt a message using Substitution Cipher

★ Encrypt and Decrypt a message using Vernan Cipher
Back to Top