35

I have implement the simple TCP server and TCP client classes which can send the message from client to server and the message will be converted to upper case on the server side, but how can I achieve transfer files from server to client and upload files from client to server. the following codes are what I have got.

TCPClient.java

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

 class TCPClient {

public static void main(String args[]) throws Exception {
        int filesize=6022386;
        int bytesRead;
        int current = 0;
    String ipAdd="";
    int portNum=0;
    boolean goes=false;
    if(goes==false){
    System.out.println("please input the ip address of the file server");
    Scanner scan=new Scanner(System.in);
    ipAdd=scan.nextLine();
    System.out.println("please input the port number of the file server");
    Scanner scan1=new Scanner(System.in);
    portNum=scan1.nextInt();
    goes=true;
    }
    System.out.println("input done");
    int timeCount=1;
    while(goes==true){
    //System.out.println("connection establishing");

    String sentence="";
    String modifiedSentence;

    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
            System.in));

    Socket clientSocket = new Socket(ipAdd, portNum);
    //System.out.println("connecting");
    //System.out.println(timeCount);
    if(timeCount==1){
    sentence="set";
    //System.out.println(sentence);


    }
    if(timeCount!=1)
        sentence = inFromUser.readLine();
            if(sentence.equals("close"))
                clientSocket.close();
            if(sentence.equals("download"))
            {
                byte [] mybytearray  = new byte [filesize];
                InputStream is = clientSocket.getInputStream();
                FileOutputStream fos = new FileOutputStream("C:\\users\\cguo\\kk.lsp");
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                bytesRead = is.read(mybytearray,0,mybytearray.length);
                current = bytesRead;
                do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
//System.out.println(end-start);
bos.close();
clientSocket.close();
            }
           // if(sentence.equals("send"))
               // clientSocket.
    timeCount--;
    //System.out.println("connecting1");
    DataOutputStream outToServer = new DataOutputStream(clientSocket
            .getOutputStream());

    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
            clientSocket.getInputStream()));


    //System.out.println("connecting2");
    //System.out.println(sentence);
    outToServer.writeBytes(sentence + "\n");

    modifiedSentence = inFromServer.readLine();

    System.out.println("FROM SERVER:" + modifiedSentence);

    clientSocket.close();

}
}

}


TCPServer.java

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

     class TCPServer {
public static void main(String args[]) throws Exception {

    Socket s = null;

    int firsttime=1;


    while (true) {
        String clientSentence;
    String capitalizedSentence="";

        ServerSocket welcomeSocket = new ServerSocket(3248);
        Socket connectionSocket = welcomeSocket.accept();

             //Socket sock = welcomeSocket.accept();


        BufferedReader inFromClient = new BufferedReader(
                new InputStreamReader(connectionSocket.getInputStream()));

        DataOutputStream outToClient = new DataOutputStream(
                connectionSocket.getOutputStream());

        clientSentence = inFromClient.readLine();
        //System.out.println(clientSentence);
                    if(clientSentence.equals("download"))
                    {
                         File myFile = new File ("C:\\Users\\cguo\\11.lsp");
  byte [] mybytearray  = new byte [(int)myFile.length()];
  FileInputStream fis = new FileInputStream(myFile);
  BufferedInputStream bis = new BufferedInputStream(fis);
  bis.read(mybytearray,0,mybytearray.length);
  OutputStream os = connectionSocket.getOutputStream();
  System.out.println("Sending...");
  os.write(mybytearray,0,mybytearray.length);
  os.flush();
  connectionSocket.close();
                    }
        if(clientSentence.equals("set"))
            {outToClient.writeBytes("connection is ");
            System.out.println("running here");
            //welcomeSocket.close();
             //outToClient.writeBytes(capitalizedSentence);
            }



        capitalizedSentence = clientSentence.toUpperCase() + "\n";


    //if(!clientSentence.equals("quit"))
           outToClient.writeBytes(capitalizedSentence+"enter the message or command: ");


        System.out.println("passed");
        //outToClient.writeBytes("enter the message or command: ");
        welcomeSocket.close();
    System.out.println("connection terminated");
    }
}

}

So, the TCPServer.java will be executed first, and then execute the TCPClient.java, and I try to use the if clause in the TCPServer.java to test what is user's input,now I really want to implement how to transfer files from both side(download and upload).Thanks.

James P.
  • 19,313
  • 27
  • 97
  • 155
starcaller
  • 979
  • 3
  • 16
  • 25

1 Answers1

26

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

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

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

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

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}
Community
  • 1
  • 1
James P.
  • 19,313
  • 27
  • 97
  • 155
  • @James:I have updated my code, however, it can't receive the file correctly, the downloaded file is empty, can you take sometime check it out please. – starcaller Jan 14 '11 at 04:06
  • Also make sure you close the `BufferedOutputStream` (the usual culprit when a file is empty). – James P. Jan 14 '11 at 04:23
  • @James: I tried that but it didn't work either. – starcaller Jan 14 '11 at 04:25
  • It'll be difficult figuring out what's happening unless there's a way to view the updated code. Have you checked the contents of the byte arrays on both side? You can output to the console using Arrays.toString( nameOfYourArray ). – James P. Jan 14 '11 at 04:29
  • I've updated my answer with some working code. Hope it helps. P.S: Adding a throws is a bad practise unless it concerns a parameter that is sent to a method. – James P. Jan 14 '11 at 06:12
  • @James: how can I make the server to receive request with file name and extension from client to determine which file the client wants to download? is there a message method to do that? Thanks for your help – starcaller Jan 16 '11 at 00:24
  • A good way to achieve that would be to have an extra `ServerSocket`, to give it a different port and to get the `InputStream` once `accept` returns a valid `Socket`. On the client side, add a second `Socket` and get its `OutputStream`. This will form a second channel where you can send information in plain text and allows commands and transfers to take place simultaneously. This is how things are done with FTP with standard ports 20 and 21. Note that the first `ServerSocket` won't be available for a second transfer as long as it's still open. – James P. Jan 16 '11 at 07:48
  • Far too many basic problems with this code. Read results ignored; completely unnecessary ByteArrayOutPutStreams; inefficient one-byte copy loops; ... -1 – user207421 Jun 28 '13 at 18:40
  • Feel free to add something :) . Stackoverflow doubles as a collaborative space. – James P. Jun 29 '13 at 00:13
  • @JamesPoulson why can't i use single `welcomeSocket` and accept different connection on same without creating it again and again. Thanks. – Trying Dec 29 '13 at 01:17
  • Thanks James above example is very helpful – Neelam Singh Feb 11 '14 at 09:14
  • How can we change the code to reverse the process. A client sending a file for the server to store. – Zee Ken Mar 29 '15 at 03:33
  • Awesome, thank you very much, James – Pavel Nov 16 '15 at 17:03
  • @JamesP. hello, I have one question, how If I have 2 clients and 1 server, the server should just transfer the file from client 1 to client 2, no need to to read it. there is any way to do it ? – asma Apr 07 '18 at 12:41
  • @asma hello, do you mean like a sort of peer-2-peer? If so you could look into code or a framework that does that. – James P. Apr 09 '18 at 02:05
  • @asma Otherwise, this sounds like FXP transferring with sends files from FTP server to server. I'd say that your clients should have minimal server capability and the proper server could send a command to clients to initiate the start of afile transfer between them. Do make sure you have failsafes to avoid any abuse like some kind of prompt for the user of a client to consent to this. – James P. Apr 09 '18 at 02:07
  • @JamesP. thank you for your reply, your above code works with me for .rtf files but it's doesn't work for .txt, can you help me in this ?! – asma Apr 15 '18 at 16:26
  • @asma the code does a byte-for-byte copy. A text file is just a series of characters encoded in ASCII or Unicode. You can inspect the file contents to see what is happening. – James P. Apr 15 '18 at 19:31
  • @JamesP. Thank you, it's working fine. But again it stuck when I want to send more than one file, or exchange the files. Any suggestion ? – asma Apr 26 '18 at 06:33
  • @asma You need to research how ServerSocket and Socket work. There is probably something to do to reset them. – James P. Apr 28 '18 at 00:40