transfer plikow nie dziala

0

witam,

na poczatku zaznacze ze jestem poczatkujacym programista. mam nastepujacy problem, naisalem aplikacje klient-serwer ktora ma za zadanie:
-najpierw zalogowac uzytkownika (login i haslo uzytkownika trzymane sa w pliku o nazwie login.txt) i to akurat dziala
-"pobrac" plik z servera zostawiajac oczywiscie zrodlo i ta opcja nie dziala. Plik o wpisanej nazwie jet tworzony, ale nic w nim nie ma.

kod servera:

//Server code for file transfer application

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

public class SFTP1Server extends Thread
{
private Socket connection;
private File currentDirectory;

//Constructor to instantiate a server socket
public SFTP1Server(Socket conn)
{
connection = conn;
}

//Server definition
public void run()
{
try
{
//Initialise variables
String returnValue = null;
File fileObj, dir;
String uName, pWord;

//Setup input and output streams for communication with client
BufferedReader in = new BufferedReader
(new InputStreamReader(connection.getInputStream()));
OutputStream out = connection.getOutputStream();
PrintWriter pWriter=new PrintWriter(out);
FileInputStream fileIn;

//Create buffer for output to client
byte[] buffer = new byte[1024];
int count;

//Setup BufferedReader and read login details from text file
BufferedReader inFromFile = new BufferedReader
(new FileReader("login.txt"));
uName = inFromFile.readLine();
pWord = inFromFile.readLine();

//Read login details from client
String userName = in.readLine();
String password = in.readLine();

//Check username and password and return authentication
//status to client
if(!(userName.equals(uName))||!(password.equals(pWord)))
{
returnValue = "f";
System.out.println("Transaction refused");
}
else
{
returnValue = "t";
System.out.println("Transaction accepted with user " + userName);
}

pWriter.println(returnValue);
pWriter.flush();

try
{
//Read file/directory name from client
String fileName = in.readLine();
fileObj = new File(fileName);

//If file is a directory, return file/directory status
//to client, followed by a list of files
if(fileObj.isDirectory())
{
returnValue = "dir";
pWriter.println(returnValue);

System.out.println("Client lists directory: "+fileName);

File[] files = fileObj.listFiles();

pWriter.println(files.length);

for(int i=0; i<files.length; i++)
{
pWriter.println(files[i]);
}
pWriter.flush();
}

//If file is a file, send bytes to client via OutputStream
else
{
System.out.println("Client downloads file: "+fileName);

//fileIn = new FileInputStream(fileObj);
//File outputFile = new File("destinationfile.txt");
//FileReader in = new FileReader(inputFile);
//FileWriter out = new FileWriter(outputFile);
//int c;
//while ((c = in.read()) != -1)
//out.write(c);
//in.close();
//out.close();
fileIn = new FileInputStream(fileObj);

while ((count = fileIn.read(buffer)) != -1)
out.write(buffer,0,count);

fileIn.close();
}

//Close input and output streams and close connection
//to indicate end of transaction
out.close();
in.close();
connection.close();

}
//Catch possible FileNotFoundException, print error message
//to server side and send error status to client
catch (FileNotFoundException nf)
{
System.out.println("File Not Found");
pWriter.println("error");
}
}
//Catch any exceptions and print error to screen
catch (IOException e) { System.err.println(e); }
}

public static void main(String args[])
{
try
{
//Create a new ServerSocket bound to specified port and accept
//client connection on that ServerSocket
ServerSocket server = new ServerSocket(2037);
while (true)
{
Socket connection = server.accept();
//Create a new thread for each client connection
SFTP1Server t = new SFTP1Server(connection);
t.start();
}
}
//Catch any exceptions and print error to screen
catch (IOException e) { System.err.println(e); }
}
}
kod klienta:

//Client code for file transfer application

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

public class SFTP1Client
{
public static void main(String args[])
{
try
{
//Initialise variables
String returnValue;
PrintWriter out;
Socket sock;
InputStream in;

//Setup BufferedReader for user input via keyboard
BufferedReader kbd= new BufferedReader
(new InputStreamReader(System.in));
BufferedReader input;

String userName;
String password;

//Get username and password from kbd and send to server
System.out.print("Username: ");
userName = kbd.readLine();

System.out.print("Password: ");
password = kbd.readLine();

while (true)
{
int count;

//Initialise byte array for incomming bytes from server
byte[] data = new byte[1024];
int port = 1523;

//Create socket on localhost machine and bind to
//specified port number
sock = new Socket("localhost", port);

//Get input stream from socket
in = sock.getInputStream();

//Create print writer to write to socket
out = new PrintWriter
(new OutputStreamWriter(sock.getOutputStream()));

//Get buffered data stream from socket
input = new BufferedReader(new InputStreamReader(in));

//Send username and password to server
out.println(userName);
out.println(password);
out.flush();

//Get authorisation status from server
returnValue = input.readLine();

//If authorisation granted, output message
if(returnValue.equals("t"))
{
System.out.println("Connection Authenticated...");
}
//If authorisation denied, output refusal message and
//re-prompt for username and password
else
{
System.out.println("Connection refused...");

//get username from kbd
System.out.print("Username: ");
userName = kbd.readLine();

//get password from kbd
System.out.print("Password: ");
password = kbd.readLine();
continue;
}

{
//Get file/directory name from user and sent to server
System.out.print("Filename: ");
String fileName = kbd.readLine();
out.println(fileName);
out.flush();

//Read file/directory status from server
returnValue = input.readLine();

//If error returned, output error message
if(returnValue.equals("error"))
System.out.println("File Not Found");

//If file is a directory, list directory on screen
else if(returnValue.equals("dir"))
{
System.out.println("File "+fileName+" is a directory\n");

int filesLength = Integer.parseInt(input.readLine());
int i;

for(i=0;i<filesLength;i++)
{
String line = input.readLine();
System.out.println(line);
}
}
//If file is a file, read incoming bytes and
//write to file named by user
else
{
FileOutputStream fileo = new FileOutputStream(new File(fileName));

PrintStream p = new PrintStream(fileo);

while (true)
{
count = in.read(data,0,1024);
if(count<=0)
break;

fileo.write(data,0,count);
}
//Close PrintWriter
p.close();
}
//Close input and output streams and close socket
out.close();
in.close();
sock.close();
}
}
}
//Catch exception and print message and error to screen
catch (IOException e)
{
System.out.println("Error has occurred!");
System.err.println(e);
}
}
}

bardzo prosze o szybka pomoc. z gory dziekuje

Pozdrawiam
Wooju

0

Tobie się nie chce sformatować kodu, a mi się nie chce czytać niesformatowanego.
pozdrawiam

0

kod servera:

//Server code for file transfer application 

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

public class SFTP1Server extends Thread 
{ 
private Socket connection; 
private File currentDirectory; 

//Constructor to instantiate a server socket 
public SFTP1Server(Socket conn) 
{ 
connection = conn; 
} 

//Server definition 
public void run() 
{ 
try 
{ 
//Initialise variables 
String returnValue = null; 
File fileObj, dir; 
String uName, pWord; 

//Setup input and output streams for communication with client 
BufferedReader in = new BufferedReader 
(new InputStreamReader(connection.getInputStream())); 
OutputStream out = connection.getOutputStream(); 
PrintWriter pWriter=new PrintWriter(out); 
FileInputStream fileIn; 

//Create buffer for output to client 
byte[] buffer = new byte[1024]; 
int count; 

//Setup BufferedReader and read login details from text file 
BufferedReader inFromFile = new BufferedReader 
(new FileReader("login.txt")); 
uName = inFromFile.readLine(); 
pWord = inFromFile.readLine(); 

//Read login details from client 
String userName = in.readLine(); 
String password = in.readLine(); 

//Check username and password and return authentication 
//status to client 
if(!(userName.equals(uName))||!(password.equals(pWord))) 
{ 
returnValue = "f"; 
System.out.println("Transaction refused"); 
} 
else 
{ 
returnValue = "t"; 
System.out.println("Transaction accepted with user " + userName); 
} 

pWriter.println(returnValue); 
pWriter.flush(); 

try 
{ 
//Read file/directory name from client 
String fileName = in.readLine(); 
fileObj = new File(fileName); 

//If file is a directory, return file/directory status 
//to client, followed by a list of files 
if(fileObj.isDirectory()) 
{ 
returnValue = "dir"; 
pWriter.println(returnValue); 

System.out.println("Client lists directory: "+fileName); 

File[] files = fileObj.listFiles(); 

pWriter.println(files.length); 

for(int i=0; i<files.length; i++) 
{ 
pWriter.println(files[i]); 
} 
pWriter.flush(); 
} 

//If file is a file, send bytes to client via OutputStream 
else 
{ 
System.out.println("Client downloads file: "+fileName); 

//fileIn = new FileInputStream(fileObj); 
//File outputFile = new File("destinationfile.txt"); 
//FileReader in = new FileReader(inputFile); 
//FileWriter out = new FileWriter(outputFile); 
//int c; 
//while ((c = in.read()) != -1) 
//out.write(c); 
//in.close(); 
//out.close(); 
fileIn = new FileInputStream(fileObj); 

while ((count = fileIn.read(buffer)) != -1) 
out.write(buffer,0,count); 

fileIn.close(); 
} 

//Close input and output streams and close connection 
//to indicate end of transaction 
out.close(); 
in.close(); 
connection.close(); 

} 
//Catch possible FileNotFoundException, print error message 
//to server side and send error status to client 
catch (FileNotFoundException nf) 
{ 
System.out.println("File Not Found"); 
pWriter.println("error"); 
} 
} 
//Catch any exceptions and print error to screen 
catch (IOException e) { System.err.println(e); } 
} 

public static void main(String args[]) 
{ 
try 
{ 
//Create a new ServerSocket bound to specified port and accept 
//client connection on that ServerSocket 
ServerSocket server = new ServerSocket(2037); 
while (true) 
{ 
Socket connection = server.accept(); 
//Create a new thread for each client connection 
SFTP1Server t = new SFTP1Server(connection); 
t.start(); 
} 
} 
//Catch any exceptions and print error to screen 
catch (IOException e) { System.err.println(e); } 
} 
} 

kod klienta:

//Client code for file transfer application 

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

public class SFTP1Client 
{ 
public static void main(String args[]) 
{ 
try 
{ 
//Initialise variables 
String returnValue; 
PrintWriter out; 
Socket sock; 
InputStream in; 

//Setup BufferedReader for user input via keyboard 
BufferedReader kbd= new BufferedReader 
(new InputStreamReader(System.in)); 
BufferedReader input; 

String userName; 
String password; 

//Get username and password from kbd and send to server 
System.out.print("Username: "); 
userName = kbd.readLine(); 

System.out.print("Password: "); 
password = kbd.readLine(); 

while (true) 
{ 
int count; 

//Initialise byte array for incomming bytes from server 
byte[] data = new byte[1024]; 
int port = 1523; 

//Create socket on localhost machine and bind to 
//specified port number 
sock = new Socket("localhost", port); 

//Get input stream from socket 
in = sock.getInputStream(); 

//Create print writer to write to socket 
out = new PrintWriter 
(new OutputStreamWriter(sock.getOutputStream())); 

//Get buffered data stream from socket 
input = new BufferedReader(new InputStreamReader(in)); 

//Send username and password to server 
out.println(userName); 
out.println(password); 
out.flush(); 

//Get authorisation status from server 
returnValue = input.readLine(); 

//If authorisation granted, output message 
if(returnValue.equals("t")) 
{ 
System.out.println("Connection Authenticated..."); 
} 
//If authorisation denied, output refusal message and 
//re-prompt for username and password 
else 
{ 
System.out.println("Connection refused..."); 

//get username from kbd 
System.out.print("Username: "); 
userName = kbd.readLine(); 

//get password from kbd 
System.out.print("Password: "); 
password = kbd.readLine(); 
continue; 
} 

{ 
//Get file/directory name from user and sent to server 
System.out.print("Filename: "); 
String fileName = kbd.readLine(); 
out.println(fileName); 
out.flush(); 

//Read file/directory status from server 
returnValue = input.readLine(); 

//If error returned, output error message 
if(returnValue.equals("error")) 
System.out.println("File Not Found"); 

//If file is a directory, list directory on screen 
else if(returnValue.equals("dir")) 
{ 
System.out.println("File "+fileName+" is a directory\n"); 

int filesLength = Integer.parseInt(input.readLine()); 
int i; 

for(i=0;i<filesLength;i++) 
{ 
String line = input.readLine(); 
System.out.println(line); 
} 
} 
//If file is a file, read incoming bytes and 
//write to file named by user 
else 
{ 
FileOutputStream fileo = new FileOutputStream(new File(fileName)); 

PrintStream p = new PrintStream(fileo); 

while (true) 
{ 
count = in.read(data,0,1024); 
if(count<=0) 
break; 

fileo.write(data,0,count); 
} 
//Close PrintWriter 
p.close(); 
} 
//Close input and output streams and close socket 
out.close(); 
in.close(); 
sock.close(); 
} 
} 
} 
//Catch exception and print message and error to screen 
catch (IOException e) 
{ 
System.out.println("Error has occurred!"); 
System.err.println(e); 
} 
} 
} 

przperaszam za zamieszanie. juz poprawiam

0

Sformatowanie, to nie tylko użycie znaczników. To przede wszystkim wcięcia w programie źródłowym.
pozdrawiam

0

kod servera:

//Server code for file transfer application

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

public class SFTP1Server extends Thread
{
    private Socket connection;
    private File currentDirectory;

    //Constructor to instantiate a server socket
    public SFTP1Server(Socket conn)
    {
        connection = conn;
    }

    //Server definition 
    public void run()
    {
        try 
        {
            //Initialise variables
            String returnValue = null;
            File fileObj, dir;
            String uName, pWord;

            //Setup input and output streams for communication with client
            BufferedReader in = new BufferedReader (new InputStreamReader(connection.getInputStream()));        
            OutputStream out = connection.getOutputStream();
            PrintWriter pWriter=new PrintWriter(out);
            FileInputStream fileIn; 

            //Create buffer for output to client
            byte[] buffer = new byte[1024];
            int count;  

            //Setup BufferedReader and read login details from text file
            BufferedReader inFromFile = new BufferedReader(new FileReader("login.txt"));
            uName = inFromFile.readLine();
            pWord = inFromFile.readLine();

            //Read login details from client
            String userName = in.readLine();
            String password = in.readLine();

            //Check username and password and return authentication 
            //status to client                      
            if(!(userName.equals(uName))||!(password.equals(pWord)))
            {
                returnValue = "f";
                System.out.println("Transaction refused");
            }
            else
            {
                returnValue = "t";
                System.out.println("Transaction accepted with user " + userName);
            }   

            pWriter.println(returnValue);
            pWriter.flush();

                try
                {   
                    //Read file/directory name from client                              
                    String fileName = in.readLine();
                    fileObj = new File(fileName);

                    //If file is a directory, return file/directory status
                    //to client, followed by a list of files
                    if(fileObj.isDirectory())
                    {
                        returnValue = "dir";
                        pWriter.println(returnValue);

                        System.out.println("Client lists directory: "+fileName);
                        File[] files = fileObj.listFiles();
                        pWriter.println(files.length);
                        for(int i=0; i<files.length; i++)
                        {   
                            pWriter.println(files[i]);
                        }
                        pWriter.flush();            
                    }

                    //If file is a file, send bytes to client via OutputStream
                    else 
                    {
                        System.out.println("Client downloads file: "+fileName);

                        fileIn = new FileInputStream(fileObj);

                        while ((count = fileIn.read(buffer)) != -1) 
                            out.write(buffer,0,count);

                        fileIn.close();
                    }

                    //Close input and output streams and close connection to indicate end of transaction
                    out.close();
                    in.close();
                    connection.close();

                }
                //Catch possible FileNotFoundException, print error message to server side and send error status to client
                catch (FileNotFoundException nf) 
                {
                    System.out.println("File Not Found");
                    pWriter.println("error");
                }
        }
        //Catch any exceptions and print error to screen
        catch (IOException e) { System.err.println(e); }
    }

    public static void main(String args[])
    {
        try
        {
            //Create a new ServerSocket bound to specified port and accept client connection on that ServerSocket
            ServerSocket server = new ServerSocket(2037);
            while (true) 
            {
                Socket connection = server.accept();
                //Create a new thread for each client connection
                SFTP1Server t = new SFTP1Server(connection);
                t.start();
            }
        }
        //Catch any exceptions and print error to screen
        catch (IOException e) { System.err.println(e); }
    }
}

kod klienta:

//Client code for file transfer application

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

public class SFTP1Client
{
    public static void main(String args[])
    {
        try 
        {
                //Initialise variables
                String returnValue;
                PrintWriter out;
                Socket sock;
                InputStream in;

                //Setup BufferedReader for user input via keyboard
                BufferedReader kbd= new BufferedReader(new InputStreamReader(System.in));
                BufferedReader input;

                String userName;
                String password;

                //Get username and password from kbd and send to server
                System.out.print("Username: ");
                userName = kbd.readLine();

                System.out.print("Password: ");
                password = kbd.readLine();

                while (true)
                {
                    int count;

                    //Initialise byte array for incomming bytes from server
                    byte[] data = new byte[1024]; 
                    int port = 1523; 

                    //Create socket on localhost machine and bind to specified port number
                    sock = new Socket("localhost", port);   

                    //Get input stream from socket      
                    in = sock.getInputStream(); 

                    //Create print writer to write to socket
                    out = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));

                    //Get buffered data stream from socket
                    input = new BufferedReader(new InputStreamReader(in));

                        //Send username and password to server
                        out.println(userName);      
                        out.println(password);
                        out.flush();

                    //Get authorisation status from server
                    returnValue = input.readLine();

                    //If authorisation granted, output message
                    if(returnValue.equals("t"))
                    {
                        System.out.println("Connection Authenticated...");
                    }
                    //If authorisation denied, output refusal message and re-prompt for username and password
                    else
                    {
                        System.out.println("Connection refused...");    

                        //get username from kbd     
                        System.out.print("Username: ");
                        userName = kbd.readLine();

                        //get password from kbd
                        System.out.print("Password: ");
                        password = kbd.readLine();
                        continue;   
                    }

                    {
                        //Get file/directory name from user and sent to server
                        System.out.print("Filename: ");
                        String fileName = kbd.readLine();
                        out.println(fileName);
                        out.flush();

                        //Read file/directory status from server
                        returnValue = input.readLine();

                        //If error returned, output error message
                        if(returnValue.equals("error"))
                            System.out.println("File Not Found");

                        //If file is a directory, list directory on screen
                        else if(returnValue.equals("dir"))
                             {
                                System.out.println("File "+fileName+" is a directory\n");

                                int filesLength = Integer.parseInt(input.readLine());
                                int i;

                                for(i=0;i<filesLength;i++)
                                {   
                                    String line = input.readLine();
                                    System.out.println(line);
                                }   
                             } 
                        //If file is a file, read incoming bytes and write to file named by user
                        else 
                        {
                            FileOutputStream fileo = new FileOutputStream(new File(fileName));

                            PrintStream p = new PrintStream(fileo);

                            while (true)
                            {   
                                count = in.read(data,0,1024);
                                if(count<=0)
                                    break;

                                fileo.write(data,0,count);
                            }
                            //Close PrintWriter
                            p.close();
                        }
                        //Close input and output streams and close socket
                        out.close(); 
                        in.close(); 
                        sock.close();   
                    }           
                }   
        }
        //Catch exception and print message and error to screen
        catch (IOException e)
        {
            System.out.println("Error has occurred!");
            System.err.println(e);
        }
    }
}
0

Nie wiem czy to jest przyczyna, prawdopodobnie tak.
Strumień, do którego zapisujesz transferowany plik

FileOutputStream fileo

nie jest zamykany

1 użytkowników online, w tym zalogowanych: 0, gości: 1, botów: 0