'Why is the socket connection not working in JAVA?

I have a difficulty in running this program. I was given to do a websocket connection using JAVA and was told to encrypt the file and send it to client and decrypt it. I used AES Encryption to encrypt and I don't change the encryption key. I have attached both the server and client code below

Server code

import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class fileserver
{
private static DataOutputStream dos=null;
private static DataInputStream dis=null;
static PrintWriter out;
static Scanner in;
static Socket socket;
public static void main(String args[]) throws Exception
{
    Scanner sc=new Scanner(System.in);
    System.out.println("1. Receive file\n2. Send file\nEnter your choice : ");
    int ch;
    ch=sc.nextInt();
    switch(ch)
    {
        case 1:
            System.out.println("RECEIVE FILE\n");
            receive();
            break;
        case 2:
            System.out.println("SEND FILE\n");
            send();
            break;
    }
}

public static void encrypt(File inputfile,File outputfile)
{
    try 
    {
        int ciphermode=Cipher.ENCRYPT_MODE;
        String key="konstantynopolitanczykowianeczka"; // 16/24/32 bit encryption
        Key secretkey=new SecretKeySpec(key.getBytes(),"AES");
        Cipher cipher=Cipher.getInstance("AES");
        cipher.init(ciphermode,secretkey);
        FileInputStream is=new FileInputStream(inputfile);
        byte[] inputbytes=new byte[(int) inputfile.length()];
        is.read(inputbytes);
        byte[] outputbytes=cipher.doFinal(inputbytes);
        FileOutputStream os=new FileOutputStream(outputfile);
        os.write(outputbytes);
        is.close();
        os.close();
    } 
    catch(Exception e)
    {
        System.out.println(e);
    }
}
public static void decrypt(File inputfile,File outputfile)
{
    try 
    {
        int ciphermode=Cipher.DECRYPT_MODE;
        String key="konstantynopolitanczykowianeczka"; // 16/24/32 bit encryption
        Key secretkey=new SecretKeySpec(key.getBytes(),"AES");
        Cipher cipher=Cipher.getInstance("AES");
        cipher.init(ciphermode,secretkey);
        FileInputStream is=new FileInputStream(inputfile);
        byte[] inputbytes=new byte[(int) inputfile.length()];
        is.read(inputbytes);
        byte[] outputbytes=cipher.doFinal(inputbytes);
        FileOutputStream os=new FileOutputStream(outputfile);
        os.write(outputbytes);
        is.close();
        os.close();
    } 
    catch(Exception e)
    {
        System.out.println(e);
    }
}
public static void receive() throws Exception
{
    Scanner sc=new Scanner(System.in);
    try(ServerSocket ss=new ServerSocket())
    {
        int port;
        String i_filepath,o_filepath,hostname;
        System.out.println("Enter the hostname : ");
        hostname=sc.nextLine();
        System.out.println("Enter the port number : ");
        port=sc.nextInt();
        InetAddress inet=null;
        try
        {
            inet=InetAddress.getByName(hostname);
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        String ip=inet.getHostAddress();
        System.out.println("The IP Address is : "+ip);
        
        System.out.println("Listening to port "+port+"...");
        Socket socket=new Socket(ip,port);
        
        dis=new DataInputStream(socket.getInputStream());
        dos=new DataOutputStream(socket.getOutputStream());
        System.out.println(new Date(System.currentTimeMillis()).toString());
        System.out.println("Hello Client");
        System.out.println("How many files do you want to store?");
        int n;
        n=sc.nextInt();
        sc.nextLine();
        for(int a=0;a<n;a++)
        {
            System.out.println("Enter the file to store : ");
            i_filepath=sc.nextLine();
            receiveFile(i_filepath);
            File encryptedFile = new File(i_filepath);
            decrypt(encryptedFile,encryptedFile);
        }
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
private static void receiveFile(String fileName) throws Exception
{
    int bytes=0;
    FileOutputStream fos=new FileOutputStream(fileName);
    long size=dis.readLong();
    byte[] b=new byte[4*1024];
    while(size>0 && (bytes=dis.read(b,0,(int)Math.min(b.length,size)))!=-1)
    {
        fos.write(b,0,bytes);
        size-=bytes;
    }
    fos.close();
}
public static void send()
{
    try
    {
        Scanner sc=new Scanner(System.in);
        String hostname,filepath,ip;
        int port;
        System.out.println("Enter the port number : ");
        port=sc.nextInt();
        sc.nextLine();
        ServerSocket ss=new ServerSocket(port);
        System.out.println("listening to port:"+port);
        Socket cs = ss.accept();
        in=new Scanner(cs.getInputStream());
        System.out.println("Server listening on port "+cs.getLocalPort()+"\n Sending on port "+cs.getPort()+"\n\n");
        System.out.println(new Date(System.currentTimeMillis()).toString());
        dis=new DataInputStream(cs.getInputStream());
        dos=new DataOutputStream(cs.getOutputStream());
        
        Thread t = new ClientHandler(cs,dis,dos);
        t.start();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
private static void sendFile(String path) throws Exception
{
    int bytes=0;
    File file=new File(path);
    FileInputStream fis=new FileInputStream(file);
    dos.writeLong(file.length());
    byte[] b=new byte[4*1024];
    while((bytes=fis.read(b))!=-1)
    {
        dos.write(b,0,bytes);
        dos.flush();
    }
    fis.close();
    }
}
class ClientHandler extends Thread 
{
private static DataOutputStream dos;
private static DataInputStream dis;
static PrintWriter out;
static Scanner in;
static Socket socket;
Scanner sc=new Scanner(System.in);
public ClientHandler(Socket socket, DataInputStream dis, DataOutputStream dos) 
{
    this.socket = socket;
    this.dis = dis;
    this.dos = dos;
}
public void run()
{        
    while (true) 
    {
        try {
            String received;
            System.out.println("What do you want? Send File..\n"+"Type Exit to terminate connection.");
            received = sc.nextLine();
            
            if(received.equals("Send File"))
            {
                try
                {
                sendF();
                }
                catch(Exception e)
                {
                    System.out.println(e);
                }
                break;
            }
            if(received.equals("Exit"))
            { 
                System.out.println("Client " + this.socket + " sends exit...");
                System.out.println("Closing this connection.");
                this.socket.close();
                System.out.println("Connection closed");
                break;
            }                
        } 
        catch (IOException e) 
        {
            System.out.println(e);
        }
    }
      
    try
    {
        this.dis.close();
        this.dos.close();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
public void sendF() throws Exception
{
    Scanner sc=new Scanner(System.in);
    char h;
    int files=0;
    String i_filepath,o_filepath,f_path,f_filepath;
    Vector<String> v=new Vector<String>();
    Vector<String> f=new Vector<String>();
    String filepath;
        do
        {
            System.out.println("Enter the file path without the file name : ");
            //sc.nextLine();
            f_path=sc.nextLine();
            System.out.println("Enter the file name to send : ");
            i_filepath=sc.nextLine();
            //dos.writeUTF(i_filepath);
            //String k=String.valueOf(i_filepath);
            //dos.writeUTF(k);
            //i_filepath="car.jpg";
            //dos.writeUTF(i_filepath);
            f_filepath=f_path+i_filepath;
            o_filepath=f_filepath+".txt";
            v.add(o_filepath);
            f.add(i_filepath);
            //File encryptedFile = new File(f_filepath);
            //File decryptedFile = new File(o_filepath);
            //encrypt(encryptedFile,decryptedFile);
            
            files++;
            
            //System.out.println(s);
            System.out.println("Enter Y to send more files or enter N to stop sending the files");
            h=sc.next().charAt(0);
            sc.nextLine();
        }while(h=='Y'||h=='y');
        
        for(int i=0;i<v.size();i++)
        {
            //String s=Integer.toString(v.size());
            //dos.writeUTF(s);
            //String s=Integer.toString(files);
            dos.writeInt(files);
            sendFile(v.get(i));
            //dos.writeUTF(f.get(i));
            //File decryptedFile=new File(v.get(i));
            //decryptedFile.delete();
        }
        dis.close();
        dos.close();
}
public static void encrypt(File inputfile,File outputfile)
{
    try 
    {
        int ciphermode=Cipher.ENCRYPT_MODE;
        String key="konstantynopolitanczykowianeczka"; // 16/24/32 bit encryption
        Key secretkey=new SecretKeySpec(key.getBytes(),"AES");
        Cipher cipher=Cipher.getInstance("AES");
        cipher.init(ciphermode,secretkey);
        FileInputStream is=new FileInputStream(inputfile);
        byte[] inputbytes=new byte[(int) inputfile.length()];
        is.read(inputbytes);
        byte[] outputbytes=cipher.doFinal(inputbytes);
        FileOutputStream os=new FileOutputStream(outputfile);
        os.write(outputbytes);
        is.close();
        os.close();
    } 
    catch(Exception e)
    {
        System.out.println(e);
    }
}
private static void sendFile(String path) throws Exception
{
    int bytes=0;
    File file=new File(path);
    FileInputStream fis=new FileInputStream(file);
    dos.writeLong(file.length());
    byte[] b=new byte[4*1024];
    while((bytes=fis.read(b))!=-1)
    {
        dos.write(b,0,bytes);
        dos.flush();
    }
    fis.close();
}
}

Client Code

import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class fileclient
{
    private static DataOutputStream dos;
private static DataInputStream dis;
static PrintWriter out;
static Scanner in;
static Socket socket;
public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);
    System.out.println("1. Receive file\n2. Send file\nEnter your choice : ");
    int ch;
    ch=sc.nextInt();
    switch(ch)
    {
        case 1:
            System.out.println("RECEIVE FILE\n");
            receive();
            break;
        case 2:
            System.out.println("SEND FILE\n");
            send();
            break;
    }
}

public static void encrypt(File inputfile,File outputfile)
{
    try
    {
        int ciphermode=Cipher.ENCRYPT_MODE;
        String key="konstantynopolitanczykowianeczka"; // 16/24/32 bit encryption
        Key secretkey=new SecretKeySpec(key.getBytes(),"AES");
        Cipher cipher=Cipher.getInstance("AES");
        cipher.init(ciphermode,secretkey);
        FileInputStream is=new FileInputStream(inputfile);
        byte[] inputbytes=new byte[(int) inputfile.length()];
        is.read(inputbytes);
        byte[] outputbytes=cipher.doFinal(inputbytes);
        FileOutputStream os=new FileOutputStream(outputfile);
        os.write(outputbytes);
        is.close();
        os.close();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
public static void decrypt(File inputfile,File outputfile)
{
    try
    {
        int ciphermode=Cipher.DECRYPT_MODE;
        String key="konstantynopolitanczykowianeczka"; // 16/24/32 bit encryption
        Key secretkey=new SecretKeySpec(key.getBytes(),"AES");
        Cipher cipher=Cipher.getInstance("AES");
        cipher.init(ciphermode,secretkey);
        FileInputStream is=new FileInputStream(inputfile);
        byte[] inputbytes=new byte[(int) inputfile.length()];
        is.read(inputbytes);
        byte[] outputbytes=cipher.doFinal(inputbytes);
        FileOutputStream os=new FileOutputStream(outputfile);
        os.write(outputbytes);
        is.close();
        os.close();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
public static void receive()
{
    Scanner sc=new Scanner(System.in);
    try(ServerSocket ss=new ServerSocket())
    {
        int port;
        String hostname;
        System.out.println("Enter the hostname : ");
        hostname=sc.nextLine();
        System.out.println("Enter the port number : ");
        port=sc.nextInt();
        InetAddress inet=null;
        try
        {
            inet=InetAddress.getByName(hostname);
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        String ip=inet.getHostAddress();
        System.out.println("The IP Address is : "+ip);

        System.out.println("Listening to port "+port+"...");
        Socket socket=new Socket(ip,port);

        dis=new DataInputStream(socket.getInputStream());
        dos=new DataOutputStream(socket.getOutputStream());
        System.out.println(new Date(System.currentTimeMillis()).toString());
        System.out.println("Hello Client");
        System.out.println("Receiving files...");
        //System.out.println("How many files do you want to store?");
        int g;
        //g=sc.nextInt();
        int n=dis.readInt();
        for(g=0;g<n;g++)
        {
            if(g==n)
            {
                g=n;
                break;
            }
        }
        //int n=Integer.parseInt(g);
        String i_filepath,o_filepath;
        System.out.println("Downloading "+n+" files..");
        sc.nextLine();
        for(int a=0;a<n;a++)
        {
            System.out.println("Enter the file name : ");
            o_filepath=sc.nextLine();
            i_filepath="E:\\New Folder\\";
            //o_filepath=dis.readUTF();
            String f_filepath=i_filepath+o_filepath;
            receiveFile(f_filepath);
            //File encryptedFile = new File(f_filepath);
            //decrypt(encryptedFile,encryptedFile);
        }

        System.out.println("Files stored successfully in E: Drive!!! ");
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
public static void de(File inputfile,File outputfile) throws Exception
{
    try
    {
        int ciphermode=Cipher.DECRYPT_MODE;
        String key="konstantynopolitanczykowianeczka"; // 16/24/32 bit encryption
        Key secretkey=new SecretKeySpec(key.getBytes(),"AES");
        Cipher cipher=Cipher.getInstance("AES");
        cipher.init(ciphermode,secretkey);
        FileInputStream is=new FileInputStream(inputfile);
        byte[] inputbytes=new byte[(int) inputfile.length()];
        is.read(inputbytes);
        byte[] outputbytes=cipher.doFinal(inputbytes);
        FileOutputStream os=new FileOutputStream(outputfile);
        os.write(outputbytes);
        is.close();
        os.close();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}

private static void receiveFile(String fileName) throws Exception
{
    int bytes=0;
    FileOutputStream fos=new FileOutputStream(fileName);
    long size=dis.readLong();
    byte[] b=new byte[4*1024];
    while(size>0 && (bytes=dis.read(b,0,(int)Math.min(b.length,size)))!=-1)
    {
        fos.write(b,0,bytes);
        size-=bytes;
    }
    fos.close();
}

public static void send()
{
    try
    {
        Scanner sc=new Scanner(System.in);
        String hostname,filepath,ip;
        int port;
        System.out.println("Enter the port number : ");
        port=sc.nextInt();
        sc.nextLine();
        ServerSocket ss=new ServerSocket(port);
        System.out.println("listening to port:"+port);
        Socket cs = ss.accept();
        in=new Scanner(cs.getInputStream());
        System.out.println("Server listening on port "+cs.getLocalPort()+"\n Sending on port "+cs.getPort()+"\n\n");
        System.out.println(new Date(System.currentTimeMillis()).toString());
        dis=new DataInputStream(cs.getInputStream());
        dos=new DataOutputStream(cs.getOutputStream());
        System.out.println("Hello Server");
        sendF();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
public static void sendF() throws Exception
{
    Scanner sc=new Scanner(System.in);
    String filepath;
    System.out.println("How many files do you want to send?");
        int n;
        n=sc.nextInt();
        sc.nextLine();
        for(int a=0;a<n;a++)
        {
            String i_filepath,o_filepath;
            System.out.println("Enter the file name to send : ");
            i_filepath=sc.nextLine();
            o_filepath=i_filepath+".txt";
            File encryptedFile = new File(i_filepath);
            File decryptedFile = new File(o_filepath);
            encrypt(encryptedFile,decryptedFile);
            sendFile(o_filepath);
            decryptedFile.delete();
        }
        dis.close();
        dos.close();
}
private static void sendFile(String path) throws Exception
{
    int bytes=0;
    File file=new File(path);
    FileInputStream fis=new FileInputStream(file);
    dos.writeLong(file.length());
    byte[] b=new byte[4*1024];
    while((bytes=fis.read(b))!=-1)
    {
        dos.write(b,0,bytes);
        dos.flush();
    }
    fis.close();
}}

I have to enter as many filepaths as I can and the client program should detect how many files that the server is sending and need to download it as the connection is established. It should contain the same name as the server sends it. When I read how many files I need to send from the server and send it, I receive the first file and decrypt it and from the second one, I have illegal block exception and EOF Exception. I require the below things:

  1. Read the number of files from the server and download it automatically in the client with the same name as the server.
  2. Need to send the files from server to multiple clients simultaneously.

Please help me with this code. Thanks in advance ;)

P.S: The code should only be in JAVA



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source